@deveco-test/deveco-cli 1.3.0-Test.11 → 1.3.0-Test.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/SKILL.md +1 -1
- package/THIRD-PARTY-LICENSES +6 -6
- package/dist/cli.js +86 -86
- package/docs.zip +0 -0
- package/index.zip +0 -0
- package/package.json +3 -3
package/dist/cli.js
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Xy=Object.defineProperty;var Zy=(n,e)=>{for(var t in e)Xy(n,t,{get:e[t],enumerable:!0})};import{bootstrap as fx}from"global-agent";import*as Yy from"path";import{program as ee}from"commander";import{red as mx}from"colorette";import{Command as iv}from"commander";import{green as oc,red as sc,yellow as ac}from"colorette";import ne from"fs";import*as $ from"path";import _t from"json5";import*as $a from"fs";import*as pe from"path";function m(n){if(process.env.DEVECO_CLI_DEBUG){let e=typeof n=="function"?n():n;console.log(`[DEBUG] ${e}`)}}var v=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let i=Number.parseInt(r,10);if(!Number.isInteger(i)||i<=0)throw new Error(`${t} must be a positive integer`);return i}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
3
|
`)}static parseDurationToSeconds(e,t="value"){let i=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!i)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let o=i[1];if((i[2]??"s")==="s")return n.parsePositiveInteger(o,t);if(!/^\d+(?:\.\d)?$/.test(o))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(o);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static filterLogsByRelativeWindow(e,t,r,i=new Date){if(!t&&!r)return e;let[o,s]=n.resolveTimeBounds(t,r,i),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let g=n.extractTimestampFromLogLine(d,i);g&&(l=n.isWithinBounds(g,o,s)),l&&c.push(d)}return c.join(`
|
|
4
|
-
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(pe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=pe.resolve(pe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=pe.normalize(e),i=pe.relative(r,t);if(i.split(pe.sep)[0]===".."||pe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||pe.isAbsolute(e)}static isPathContained(e,t){let r=pe.resolve(t,e),i=pe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=Ha.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=pe.resolve(i,e),s;try{s=Ha.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var V=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=$.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=$.join(e,"build-profile.json5");if(!re.existsSync(t))return null;try{let r=re.readFileSync(t,"utf-8"),i=Ft.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"src","main","module.json5");if(!re.existsSync(i))return"entry";try{let o=re.readFileSync(i,"utf-8");return Ft.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=$.normalize(e);for(let r of this.profile.modules){let i=$.normalize($.join(this.rootDir,r.srcPath)),o=i+$.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"build-profile.json5");if(!re.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);try{let o=re.readFileSync(i,"utf-8");return Ft.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(){let e=$.join(this.rootDir,"AppScope","app.json5");if(re.existsSync(e))try{let t=re.readFileSync(e,"utf-8"),r=Ft.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=$.join(this.rootDir,"AppScope","app.json5");if(!re.existsSync(e))return!1;try{let t=re.readFileSync(e,"utf-8");return Ft.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=E.resolvePathWithinRoot(this.rootDir,r.srcPath),o=$.join(i,"src","main","module.json5");if(!re.existsSync(o))return"EntryAbility";try{let s=re.readFileSync(o,"utf-8"),c=Ft.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=E.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"oh-package.json5");if(!re.existsSync(i))return[];let o=[];try{let s=re.readFileSync(i,"utf-8"),c=Ft.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=$.join(t.srcPath,d),P=E.resolvePathWithinRoot(this.rootDir,w),O=this.profile.modules.find(ne=>$.resolve(this.rootDir,ne.srcPath)===P);O&&o.push(O.name)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new Error(`Module '${e}' not found. Available modules: ${l}`)}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!re.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let P=this.getSignedHapName(c,o.srcPath,i,t);P&&(d=P)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!re.existsSync(w))throw new Error(`Generated package file not found in ${w}.`);return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=$.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!re.existsSync(l))throw new Error(`Remote HSP dependency not found: ${l}`);s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return re.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=E.resolvePathWithinRoot(this.rootDir,e),o=$.resolve(i,"build",t,...r);return E.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=re.readFileSync(e,"utf-8");r=Ft.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=$.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 tu}from"child_process";import X from"fs";import*as ke from"os";import*as S from"path";import Jd from"fs";import*as lo from"os";import*as co from"path";import Zy from"regedit";import{execFileSync as Ky}from"child_process";import Vd from"fs";import*as zd from"os";import*as $a from"path";import{compare as Jy}from"semver";function Gd(n,e){return Jy(n,e)}function Gn(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function ao(n,e){let t=$a.join(n,"Contents","Info.plist");if(!Vd.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=Ky(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function Xy(n){let e=ao(n,"CFBundleShortVersionString");if(!e)return ao(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[ao(n,"CFBundleVersion"),ao(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Wr(n){if(zd.platform()==="darwin")return Xy(n);let e=$a.join(n,"product-info.json");try{let t=JSON.parse(Vd.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function Qy(n){return n.filter(e=>{try{return Jd.statSync(e).isDirectory()}catch{return!1}})}function ew(){let n=[];for(let e of[co.join(lo.homedir(),"Applications"),"/Applications"])try{n.push(...Jd.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>co.join(e,t)))}catch{}return n}function qd(n){return new Promise((e,t)=>Zy.list(n,(r,i)=>r?t(r):e(i)))}async function Yd(n,e,t){let i=((await qd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await qd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function tw(){let n=[co.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await Yd(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await Yd(e,()=>!0,""))}catch{}return n}async function Kd(){let n=lo.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?ew():await tw(),t=Qy(e).flatMap(r=>{let i=Wr(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,i)=>Gn(i.version,r.version)>0?i:r)}import*as Xd from"fs";import*as Se from"path";function Ua(n,e){let t=Se.relative(e,n);return t===""||!Se.isAbsolute(t)&&!t.startsWith(`..${Se.sep}`)&&t!==".."}function ct(n){let e=Se.resolve(n),t=[],r=e;for(;;)try{let i=Xd.realpathSync(r);return t.length===0?i:Se.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Se.dirname(r);if(o===r)return e;t.push(Se.basename(r)),r=o}}function uo(n,e){let t=ct(e),r=ct(n);return Ua(r,t)?r:null}function Ba(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function po(n){let e=Ba(n);if(!e)throw new Error("Path must not be empty.");return ct(e)}var Gr={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},fo={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var fe={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},Je={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},vn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Vr={baseUrl:Je.LOGIN_URL,authUrl:Je.AUTH_APPLY_PATH,tempTokenCheckUrl:Je.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Je.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Je.LOGIN_SUCCESS_PATH,failedRedirectUrl:Je.LOGIN_FAILED_PATH,logoutUrl:Je.LOGOUT_PATH,agcTeamListUrl:Je.AGC_TEAM_LIST_URL,appId:fe.APP_ID,timeout:Gr.LOGIN_TIMEOUT_MS,countryCode:"CN"};var Wa="https://matrix.openharmony.cn",Ke={TAGS_API_URL:`${Wa}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Wa}/api/registry/skill/skills`,SKILL_API_BASE:`${Wa}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Xe={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"}};import{homedir as vt}from"os";import Re from"path";var lt="deveco-mcp";var jt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Re.join(vt(),".config","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(vt(),"AppData","Roaming"),"Trae CN","User"):Re.join(vt(),"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(vt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Re.join(vt(),".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(vt(),"AppData","Roaming"),"Qoder","SharedClientCache"):Re.join(vt(),"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(vt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Re.join(vt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Qd(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Zd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function eu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function mo(n,e){return n.format==="opencode"?Qd(e):n.format==="claude-code"||n.format==="codex"?Zd(e):eu(e)}var Ze={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Ga="https://developer.huawei.com/consumer/cn/download/";var nw=/^#\s*Version:\s*(\S+)/,rw="26.0.0.810";function iw(n){try{let e=JSON.parse(X.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function ow(n){let e=S.join(n,"default","openharmony");return[S.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>S.join(e,t,"oh-uni-package.json"))]}var I=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;static verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}verify(e){return n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Gn(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){this.assertStudio(),n.assertMinimumVersion(Wr(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${o}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${o}`);if(Gn(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
5
|
-
${
|
|
4
|
+
`)}static resolveTimeBounds(e,t,r){let i=e?new Date(r.getTime()-e*1e3):null,o=t?new Date(r.getTime()-t*1e3):null;return i&&o?i<o?[i,o]:[o,i]:i?[i,r]:o?[null,o]:[null,null]}static isWithinBounds(e,t,r){let i=e.getTime(),o=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(o!==null&&i<o||s!==null&&i>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let i=t.getFullYear(),o=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",g=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(i,o,s,a,c,l,g);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(i-1),w}static assertBundleName(e){if(!/^[A-Za-z0-9_.]{1,128}$/.test(e))throw new Error(`Invalid bundleName: ${JSON.stringify(e)}`)}static assertBundleNameStrict(e){if(e.length<7||e.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${e.length}`);if(e.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let t=e.split(".");if(t.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let r=/^[a-zA-Z0-9_]+$/;for(let i=0;i<t.length;i++){let o=t[i];if(!r.test(o))throw new Error(`Segment "${o}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(i===0){if(!/^[a-zA-Z]/.test(o))throw new Error(`First segment "${o}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(o))throw new Error(`Segment "${o}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(o))throw new Error(`Segment "${o}" must end with a letter or digit.`)}}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let i=r.charCodeAt(0);return i<=n.ASCII_CONTROL_MAX||i===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return m(`quotePosixShellArg: ${e} -> ${r}`),r}static assertCrashFilename(e){if(!/^\w+-[\w.]+-\d+-\d+$/.test(e))throw new Error(`Invalid crash log filename: ${JSON.stringify(e)}`)}static assertHilogLevel(e){if(!/^[DIWEF]$/.test(e))throw new Error(`Invalid log level: ${e}`)}static resolvePathWithinRoot(e,t){if(pe.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=pe.resolve(pe.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=pe.normalize(e),i=pe.relative(r,t);if(i.split(pe.sep)[0]===".."||pe.isAbsolute(i))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||pe.isAbsolute(e)}static isPathContained(e,t){let r=pe.resolve(t,e),i=pe.relative(t,r);return n.isPathEscaping(i)?{contained:!1,reason:`Path traversal project root directory: ${e}`}:{contained:!0}}static isPathContainedWithSymlink(e,t){let r=n.isPathContained(e,t);if(!r.contained)return r;let i;try{i=$a.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let o=pe.resolve(i,e),s;try{s=$a.realpathSync(o)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${o}`}}return n.isPathContained(s,i)}};var V=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let i=$.dirname(t);if(i===t)break;t=i}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=$.join(e,"build-profile.json5");if(!ne.existsSync(t))return null;try{let r=ne.readFileSync(t,"utf-8"),i=_t.parse(r);return i.app?i:null}catch(r){return console.error(`Error parsing ${t}:`,r),null}}getRunnableModuleNames(){return this.profile.modules.map(e=>e.name).filter(e=>this.getModuleType(e)!=="har").join(", ")}getModuleType(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=v.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"src","main","module.json5");if(!ne.existsSync(i))return"entry";try{let o=ne.readFileSync(i,"utf-8");return _t.parse(o)?.module?.type||"entry"}catch(o){return console.warn(`Warning: Failed to parse ${i}:`,o),"entry"}}findOwningModule(e){let t=$.normalize(e);for(let r of this.profile.modules){let i=$.normalize($.join(this.rootDir,r.srcPath)),o=i+$.sep;if(t.startsWith(o)||t===i)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(o=>o.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=v.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"build-profile.json5");if(!ne.existsSync(i))throw new Error(`Build profile for module '${e}' not found at ${i}.`);try{let o=ne.readFileSync(i,"utf-8");return _t.parse(o)}catch(o){throw new Error(`Failed to parse module build profile at ${i}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}}getBundleName(){let e=$.join(this.rootDir,"AppScope","app.json5");if(ne.existsSync(e))try{let t=ne.readFileSync(e,"utf-8"),r=_t.parse(t);if(r?.app?.bundleName)return r.app.bundleName}catch(t){console.warn(`Warning: Failed to parse ${e}:`,t)}throw new Error("Could not find bundleName in AppScope/app.json5.")}isAtomicService(){let e=$.join(this.rootDir,"AppScope","app.json5");if(!ne.existsSync(e))return!1;try{let t=ne.readFileSync(e,"utf-8");return _t.parse(t)?.app?.bundleType==="atomicService"}catch{return!1}}getMainAbility(e,t){if(t)return t;let r=this.profile.modules.find(s=>s.name===e);if(!r)return"EntryAbility";let i=v.resolvePathWithinRoot(this.rootDir,r.srcPath),o=$.join(i,"src","main","module.json5");if(!ne.existsSync(o))return"EntryAbility";try{let s=ne.readFileSync(o,"utf-8"),c=_t.parse(s)?.module?.abilities||[];if(c.length===0)return"EntryAbility";let l=c.find(d=>d.name==="EntryAbility");return l?l.name:c[0].name}catch(s){return console.warn(`Warning: Failed to parse ${o}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(i=>i.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=v.resolvePathWithinRoot(this.rootDir,t.srcPath),i=$.join(r,"oh-package.json5");if(!ne.existsSync(i))return[];let o=[];try{let s=ne.readFileSync(i,"utf-8"),c=_t.parse(s)?.dependencies||{};for(let l of Object.values(c)){if(typeof l!="string")continue;let d=l;if(!(d.startsWith("file:")||d.startsWith(".")||d.startsWith("..")))continue;d.startsWith("file:")&&(d=d.substring(5));let w=$.join(t.srcPath,d),P=v.resolvePathWithinRoot(this.rootDir,w),O=this.profile.modules.find(te=>$.resolve(this.rootDir,te.srcPath)===P);O&&o.push(O.name)}}catch(s){m(`Failed to get module dependencies: ${s instanceof Error?s.message:String(s)}`)}return o}collectNonHarDependentModuleList(e){let t=[],r=[],i=new Set;for(r.push(e),i.add(e);r.length>0;){let o=r.shift();this.getModuleType(o)!=="har"&&t.push(o);let a=this.getModuleDependencies(o);for(let c of a)i.has(c)||(r.push(c),i.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let i=this.profile.modules.find(l=>l.name===e);if(!i){let l=this.getRunnableModuleNames();throw new Error(`Module '${e}' not found. Available modules: ${l}`)}let o=this.getModuleType(e)==="shared",s=o?"hspName":"hapName",a=this.buildOutputPath(i.srcPath,r,["intermediates",o?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!ne.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode:i,isShared:o,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,i="default"){let{moduleNode:o,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,i),{packageName:c,isSigned:l}=a,d=c;if(!l){let P=this.getSignedHapName(c,o.srcPath,i,t);P&&(d=P)}let g=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(g))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(o.srcPath,i,["outputs",t,d]);if(!ne.existsSync(w))throw new Error(`Generated package file not found in ${w}.`);return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:i,metadata:o}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of o.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=$.isAbsolute(c)?c:this.buildOutputPath(i.srcPath,r,["outputs",t,c]);if(!ne.existsSync(l))throw new Error(`Remote HSP dependency not found: ${l}`);s.push(l)}return s}getSignedHapName(e,t,r,i){let o=null;if(e.endsWith("-unsigned.hap")?o=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(o=e.replace("-unsigned.hsp","-signed.hsp")),!o)return null;let s=this.buildOutputPath(t,r,["outputs",i,o]);return ne.existsSync(s)?o:null}buildOutputPath(e,t,r){let i=v.resolvePathWithinRoot(this.rootDir,e),o=$.resolve(i,"build",t,...r);return v.ensurePathWithinRoot(this.rootDir,o)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(i=>!!(i.hspName&&i.hspPath)).map(i=>({hspName:i.hspName,hspPath:i.hspPath})):[]})}parseOutputMetadata(e,t){let r;try{let c=ne.readFileSync(e,"utf-8");r=_t.parse(c)}catch(c){throw new Error(`Failed to parse output metadata at ${e}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}let i,o=!1,s=Array.isArray(r)?r:[r];for(let c of s)i||(i=c[t]),o||(o=c.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(i);let a=this.collectRemoteHsps(s);return{packageName:i,isSigned:o,dependRemoteHsps:a}}validatePackageName(e){let t=$.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 nu}from"child_process";import se from"fs";import*as Ze from"os";import*as E from"path";import Kd from"fs";import*as lo from"os";import*as co from"path";import nw from"regedit";import{execFileSync as ew}from"child_process";import zd from"fs";import*as qd from"os";import*as Ua from"path";import{compare as Qy}from"semver";function Vd(n,e){return Qy(n,e)}function Gn(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let i=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(i)return i}return 0}function ao(n,e){let t=Ua.join(n,"Contents","Info.plist");if(!zd.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,i]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let o=ew(r,i,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(o&&!o.includes("Does Not Exist"))return o}catch{}}function tw(n){let e=ao(n,"CFBundleShortVersionString");if(!e)return ao(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[ao(n,"CFBundleVersion"),ao(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let i of r){let o=i?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(o&&/^\d+$/.test(o))return`${e}.${o}`}return e}function Wr(n){if(qd.platform()==="darwin")return tw(n);let e=Ua.join(n,"product-info.json");try{let t=JSON.parse(zd.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function rw(n){return n.filter(e=>{try{return Kd.statSync(e).isDirectory()}catch{return!1}})}function iw(){let n=[];for(let e of[co.join(lo.homedir(),"Applications"),"/Applications"])try{n.push(...Kd.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>co.join(e,t)))}catch{}return n}function Yd(n){return new Promise((e,t)=>nw.list(n,(r,i)=>r?t(r):e(i)))}async function Jd(n,e,t){let i=((await Yd([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(i.length===0)return[];let o=await Yd(i);return i.flatMap(s=>{let a=o[s]?.values?.[t]?.value;return a?[a]:[]})}async function ow(){let n=[co.join("C:","Program Files","Huawei","DevEco Studio")];for(let e of["HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall","HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"])try{n.push(...await Jd(e,t=>t.normalize("NFKC").trim().toLowerCase().startsWith("deveco studio"),"InstallLocation"))}catch{}for(let e of["HKLM\\SOFTWARE\\Huawei\\DevEco Studio","HKLM\\SOFTWARE\\WOW6432Node\\Huawei\\DevEco Studio"])try{n.push(...await Jd(e,()=>!0,""))}catch{}return n}async function Xd(){let n=lo.platform();if(n==="linux")throw new Error("DevEco Studio is not available on Linux. Set DEVECO_CLI_CLT_PATH to a Command Line Tools installation.");let e=n==="darwin"?iw():await ow(),t=rw(e).flatMap(r=>{let i=Wr(r);return i?(m(`[ToolProvider] ${r} => version ${i}`),[{root:r,version:i}]):(m(`[ToolProvider] Skipping ${r}: could not read version`),[])});if(!t.length)throw new Error("DevEco Studio installation not found in default locations.");return t.reduce((r,i)=>Gn(i.version,r.version)>0?i:r)}import*as Zd from"fs";import*as Se from"path";function Ba(n,e){let t=Se.relative(e,n);return t===""||!Se.isAbsolute(t)&&!t.startsWith(`..${Se.sep}`)&&t!==".."}function ct(n){let e=Se.resolve(n),t=[],r=e;for(;;)try{let i=Zd.realpathSync(r);return t.length===0?i:Se.join(i,...t.reverse())}catch(i){if(i.code!=="ENOENT")throw i;let o=Se.dirname(r);if(o===r)return e;t.push(Se.basename(r)),r=o}}function uo(n,e){let t=ct(e),r=ct(n);return Ba(r,t)?r:null}function Wa(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function po(n){let e=Wa(n);if(!e)throw new Error("Path must not be empty.");return ct(e)}var Gr={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},fo={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var fe={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},Je={LOGIN_URL:"https://devecostudio.huawei.com",CN_LOGIN_URL:"https://cn.devecostudio.huawei.com",AUTH_APPLY_PATH:"console/DevEcoIDE/apply",TEMP_TOKEN_CHECK_PATH:"authrouter/auth/api/temptoken/check",JWT_TOKEN_CHECK_PATH:"authrouter/auth/api/jwToken/check",LOGIN_SUCCESS_PATH:"console/DevEcoCLI/loginSuccess",LOGIN_FAILED_PATH:"console/DevEcoCLI/loginFailed",LOGOUT_PATH:"authrouter/auth/api/logout",AGC_TEAM_LIST_URL:"https://connect-api.cloud.huawei.com/api/ups/user-permission-service/v1/user-team-list"},vn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},Vr={baseUrl:Je.LOGIN_URL,authUrl:Je.AUTH_APPLY_PATH,tempTokenCheckUrl:Je.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:Je.JWT_TOKEN_CHECK_PATH,successRedirectUrl:Je.LOGIN_SUCCESS_PATH,failedRedirectUrl:Je.LOGIN_FAILED_PATH,logoutUrl:Je.LOGOUT_PATH,agcTeamListUrl:Je.AGC_TEAM_LIST_URL,appId:fe.APP_ID,timeout:Gr.LOGIN_TIMEOUT_MS,countryCode:"CN"};var Ga="https://matrix.openharmony.cn",Oe={TAGS_API_URL:`${Ga}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${Ga}/api/registry/skill/skills`,SKILL_API_BASE:`${Ga}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,DEFAULT_MAX_PAGES:100,SUCCESS_CODE:"20000"},Ke={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"},"claude-code":{path:".claude/skills",projectPath:".claude/skills",displayName:"claude-code"},codex:{path:".codex/skills",displayName:"codex"},atomcode:{path:".atomcode/skills",displayName:"atomcode"}};import{homedir as wt}from"os";import ke from"path";var lt="deveco-mcp";var Ft={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:ke.join(wt(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:ke.join(process.platform==="win32"?ke.join(process.env.APPDATA??ke.join(wt(),"AppData","Roaming"),"Trae CN","User"):ke.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:ke.join(wt(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:ke.join(wt(),".codebuddy","mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:ke.join(process.platform==="win32"?ke.join(process.env.APPDATA??ke.join(wt(),"AppData","Roaming"),"Qoder","SharedClientCache"):ke.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:ke.join(wt(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:ke.join(wt(),".codex","config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function eu(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function Qd(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function tu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function mo(n,e){return n.format==="opencode"?eu(e):n.format==="claude-code"||n.format==="codex"?Qd(e):tu(e)}var Xe={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var Va="https://developer.huawei.com/consumer/cn/download/";var sw=/^#\s*Version:\s*(\S+)/,aw="26.0.0.810";function cw(n){try{let e=JSON.parse(se.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch(e){m(`[ToolProvider] Failed to parse API level from ${n}: ${e instanceof Error?e.message:String(e)}`);return}}function lw(n){let e=E.join(n,"default","openharmony");return[E.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>E.join(e,t,"oh-uni-package.json"))]}var A=class n{constructor(e,t,r,i,o,s,a,c,l,d){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=i;this._ohpmJsPath=o;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;static verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}verify(e){return n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e}assertJava(){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return Gn(e,t)}static async checkVersion(){let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath)}assertVersion(){if(this._sourceType==="clt"){this.assertCltVersion();return}this.assertIdeVersion()}assertCltVersion(e="26.0.0"){if(this._sourceType!=="clt")throw new Error("This operation requires Command Line Tools.");n.assertMinimumVersion(n.readCltVersion(this._toolchainRoot),"Command Line Tools","version.txt",e,this._toolchainRoot)}assertIdeVersion(e="6.1.0"){this.assertStudio(),n.assertMinimumVersion(Wr(this._toolchainRoot),"DevEco Studio","product-info.json / Info.plist",e,this._toolchainRoot)}require(e){if(this._sourceType==="clt"){this.requireClt(e.clt);return}this.requireIde(e.studio)}requireClt(e){if(e===!1)throw new Error("This operation is not supported in Command Line Tools mode.");typeof e=="string"&&this.assertCltVersion(e)}requireIde(e){if(e===!1)throw new Error("This operation is not supported in DevEco Studio mode.");typeof e=="string"&&this.assertIdeVersion(e)}static assertMinimumVersion(e,t,r,i,o){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${o}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${o}`);if(Gn(e,i)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${i}. Upgrade before using deveco-cli:
|
|
5
|
+
${Va}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),i=r.find(n.isFile);if(!i){let a=t==="studio"?"Code Linter not found in DevEco Studio.":"Code Linter not found in DevEco Command Line Tools.";throw new Error(`${a}
|
|
6
6
|
Searched paths:
|
|
7
7
|
${r.join(`
|
|
8
|
-
`)}`)}let o=ct(e),s=ct(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=ke.platform()==="darwin"?["Contents"]:[];return[S.join(e,...r,"plugins","codelinter","run","index.js"),S.join(e,...r,"plugins","codelinter","index.js"),S.join(e,...r,"tools","codelinter","bin","codelinter.js"),S.join(e,...r,"tools","codelinter","codelinter.js")]}return[S.join(e,"codelinter","index.js"),S.join(e,"codelinter","run","index.js"),S.join(e,"tool","codelinter","bin","codelinter.js"),S.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return X.existsSync(S.join(e,"version.txt"));let r=ke.platform()==="darwin"?S.join(e,"Contents"):e,i=ke.platform()==="darwin"?S.join(r,"Info.plist"):S.join(r,"product-info.json");if(!X.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(X.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=S.join(e,"sdk"),r=ke.platform()==="win32",i=r?".exe":"";return{nodePath:r?S.join(e,"tool","node","node.exe"):S.join(e,"tool","node","bin","node"),ohpmJsPath:S.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:S.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:S.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=ke.platform()==="darwin",r=ke.platform()==="win32",i=t?S.join(e,"Contents"):e,o=S.join(i,"tools"),s=S.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?S.join(o,"node","node.exe"):S.join(o,"node","bin","node"),ohpmJsPath:S.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:S.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?S.join(e,"jbr","bin","java.exe"):t?S.join(i,"jbr","Contents","Home","bin","java"):S.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:S.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:S.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return X.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return X.existsSync(e)&&X.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Kd();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=po(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&ke.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=ct(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(uo(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${S.sep}Contents`,r=S.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return X.readFileSync(S.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(nw)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(S.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(S.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return X.realpathSync(o);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(ke.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>S.join(e,r)).find(X.existsSync)}getMaxApiLevel(){for(let e of ow(this.sdkPath)){let t=iw(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=ke.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=S.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=S.join(r,"resources","apiChange"),o=S.join(r,"api-change-scan.js");if(!X.existsSync(i)||!X.existsSync(o)){let s=Wr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${rw}. Upgrade before using 'check compat' at ${Ga}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!X.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=ke.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&S.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!X.statSync(e).isFile())throw new Error;X.accessSync(e,X.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=S.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=X.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=S.join(S.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=X.mkdtempSync(S.join(ke.tmpdir(),"deveco-verify-")),i=S.join(r,"Verify-Signature.ps1");X.writeFileSync(i,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let o=tu(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",i,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(o);return{signed:Number(s.Status)===0}}catch(o){return m(`[ToolProvider] verify Windows Signature, error msg: ${o}`),{signed:!1}}finally{X.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return tu("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as sw}from"execa";import*as Ht from"path";import*as ho from"fs";import*as nu from"os";var Oe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=Ht.dirname(e.javaPath),o=`${i}${Ht.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=Ht.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!ho.existsSync(t))return null;try{let r=ho.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||Ht.join(nu.homedir(),".hvigor");return Ht.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),await this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await sw(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as aw}from"execa";var Vn=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`),await aw(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as cw}from"fs/promises";import{dirname as lw,resolve as dw}from"path";import{execa as uw}from"execa";import{lock as Va,check as LL}from"proper-lockfile";function za(n){return dw(n,".hvigor",".build-lock")}function pw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function ru(n){let e=lw(za(n));if(await cw(e,{recursive:!0}),process.platform==="win32")try{await uw("attrib",["+h",e])}catch{}}async function fw(n,e){let t=new AbortController,r=pw(e);await ru(n);let i={lockfilePath:za(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await Va(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await Va(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Sn(n,e,t){let{release:r,signal:i}=await fw(n,t);try{return await e(i)}finally{await r()}}async function go(n,e){let t=new AbortController;await ru(n);let r={lockfilePath:za(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await Va(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as $t from"fs";import*as En from"path";import mw from"json5";var hw=1e3;function wo(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=En.join(n,Ze.SYNC_OUTPUT_PATH);if(!$t.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=$t.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=gw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=En.join(n,Ze.OH_PACKAGE_JSON5),o=yo(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=En.join(n,Ze.BUILD_PROFILE_JSON5),a=yo(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=En.join(n,l.srcPath,Ze.OH_PACKAGE_JSON5),g=yo(d,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=En.join(n,l.srcPath,Ze.BUILD_PROFILE_JSON5),P=yo(w,t,l.name);if(P.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${P.reason}`),P}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function yo(n,e,t){if(!$t.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=$t.statSync(n).mtimeMs;return r-e>hw?{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 gw(n){let e=En.join(n,Ze.BUILD_PROFILE_JSON5);try{let t=$t.readFileSync(e,"utf-8");if(!t.trim())return null;let r=mw.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as xe from"fs";import*as Fe from"path";import*as wu from"util";import*as M from"fs";import*as Ro from"path";import T from"fs";import*as vo from"os";import*as A from"path";import yw from"json5";var qa="Huawei";var su=3,au=3,iu="DevEco Studio",cu={DevEcoStudio:"deveco_studio"};function So(n){if(!T.existsSync(n)||!T.statSync(n).isDirectory())return!1;let e=T.existsSync(A.join(n,"build-profile.json5")),t=T.existsSync(A.join(n,"hvigorfile.js"))||T.existsSync(A.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=T.readFileSync(A.join(n,"build-profile.json5"),"utf-8");return yw.parse(r).app!==void 0}catch{return!1}}function Ya(n,e,t){if(e>=t)return null;let r=ww(n),i=vw(r);if(i)return i;for(let o of r){let s=Ya(o,e+1,t);if(s)return s}return null}function ww(n){try{let e=T.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(A.join(n,r.name));return t}catch{return[]}}function vw(n){for(let e of n)if(So(e))return e;return null}function St(n){if(!n||n.trim()==="")return null;let e=A.resolve(n),t;try{t=T.realpathSync(e)}catch{t=e}if(!T.existsSync(t))return null;if(So(t))return t;let r=t;for(let i=1;i<=3;i++){let o=A.dirname(r);if(o===r)break;if(So(o))return o;r=o}if(T.statSync(t).isDirectory()){let i=Ya(t,0,su);if(i)return i}return null}function Eo(n){if(!n||n.trim()==="")return null;let e=A.resolve(n),t;try{t=T.realpathSync(e)}catch{t=e}return!T.existsSync(t)||!T.statSync(t).isDirectory()?null:So(t)?t:Ya(t,0,su)}function Sw(n){let e=n??Ka();if(!e)return null;let t=null;if(process.platform==="win32"?t=A.join(e,"plugins","openharmony"):process.platform==="darwin"&&(t=A.join(e,"contents","plugins","openharmony")),t){let o=A.join(t,"ace-server","out","index.js");if(T.existsSync(o))return t}let r=A.join(e,"arkts-lsp","lib"),i=A.join(r,"out","index.js");return T.existsSync(i)?r:null}function Ja(n){let e=Cw(n??""),t=lu(e);return A.join(t,"sdk")}function bo(n){return{sdkPath:Ja(n),arktsLangServerPath:Sw(n)}}function zr(n,e){let t=e?A.join("standardIndex","index.js"):"index.js";return T.existsSync(A.join(n,"ace-server"))?A.join(n,"ace-server","out",t):A.join(n,"out",t)}function Po(n){return T.existsSync(zr(n,!0))}var Ew=["default","openharmony","native","llvm","bin","clangd"],bw=[".idea",".deveco","cxx","compile_commands.json"];function Co(n){let e=A.join(n,...Ew),t=process.platform==="win32"?e+".exe":e;return T.existsSync(t)?t:null}function qr(n){return A.join(n,...bw)}function Ka(){if(process.platform==="win32"){let n=[A.join("C:\\Program Files",qa,iu),A.join("C:\\Program Files (x86)",qa,iu)];return ou(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",A.join(process.env.HOME??"","Applications","DevEco Studio.app")];return ou(n)}return null}function ou(n){for(let e of n)if(T.existsSync(e))return e;return null}function lu(n){return process.platform==="darwin"?A.join(n,"Contents"):n}function Pw(n){if(!n||!T.existsSync(n)||!du(n))return!1;let e=lu(n);return[A.join(e,"plugins","openharmony"),A.join(e,"sdk"),A.join(e,"tools")].some(r=>T.existsSync(r))}function du(n){try{return T.statSync(n).isDirectory()}catch{return!1}}function Xa(n,e){return!n||!T.existsSync(n)?!1:e===cu.DevEcoStudio?Pw(n):!1}function Cw(n,e=cu.DevEcoStudio){if(!n)return"";if(Xa(n,e))return n;let t=Iw(n,e);if(t)return t;let r=Aw(n,e);return r||n}function Iw(n,e){let t=n;for(let r=0;r<au;r++){let i=A.dirname(t);if(!i||i===t)break;if(Xa(i,e))return i;t=i}return null}function Aw(n,e){if(!T.existsSync(n)||!du(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=au)continue;let o=Dw(r,i,e,t);if(o)return o}return null}function Dw(n,e,t,r){let i;try{i=T.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=A.join(n,o.name);if(Xa(s,t))return s;r.push({p:s,depth:e+1})}return null}function uu(n){return new Promise(e=>setTimeout(e,n))}var Rw=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function bn(n){let e=A.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Rw.has(e)}function Io(n){return A.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ae(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function kw(n){return ae(n)}function Pn(n){let e=kw(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Ut(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??A.join(vo.homedir(),"AppData","Local");return A.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?A.join(vo.homedir(),"Library","Logs","devecocli-mcp-server"):A.join(vo.homedir(),".local","share","devecocli-mcp-server","logs")}function pu(n,e){let t=Tw(e),r=xw(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=Lw(t,n,s);return Nw(e,a),i}function Tw(n){let e;try{e=T.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function xw(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Lw(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function Nw(n,e){try{T.mkdirSync(A.dirname(n),{recursive:!0})}catch{}try{T.writeFileSync(n,e.join(`
|
|
8
|
+
`)}`)}let o=ct(e),s=ct(i);return n.assertInsideRoot(s,o,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=Ze.platform()==="darwin"?["Contents"]:[];return[E.join(e,...r,"plugins","codelinter","run","index.js"),E.join(e,...r,"plugins","codelinter","index.js"),E.join(e,...r,"tools","codelinter","bin","codelinter.js"),E.join(e,...r,"tools","codelinter","codelinter.js")]}return[E.join(e,"codelinter","index.js"),E.join(e,"codelinter","run","index.js"),E.join(e,"tool","codelinter","bin","codelinter.js"),E.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return se.existsSync(E.join(e,"version.txt"));let r=Ze.platform()==="darwin"?E.join(e,"Contents"):e,i=Ze.platform()==="darwin"?E.join(r,"Info.plist"):E.join(r,"product-info.json");if(!se.existsSync(i))return!1;let o=n.buildToolPaths(e,"studio");return[o.nodePath,o.ohpmJsPath,o.hvigorJsPath].every(se.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=E.join(e,"sdk"),r=Ze.platform()==="win32",i=r?".exe":"";return{nodePath:r?E.join(e,"tool","node","node.exe"):E.join(e,"tool","node","bin","node"),ohpmJsPath:E.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:E.join(t,"default","openharmony","toolchains",`hdc${i}`),emulatorPath:E.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=Ze.platform()==="darwin",r=Ze.platform()==="win32",i=t?E.join(e,"Contents"):e,o=E.join(i,"tools"),s=E.join(i,"sdk"),a=r?".exe":"";return{nodePath:r?E.join(o,"node","node.exe"):E.join(o,"node","bin","node"),ohpmJsPath:E.join(o,"ohpm","bin","pm-cli.js"),hvigorJsPath:E.join(o,"hvigor","bin","hvigorw.js"),javaPath:r?E.join(e,"jbr","bin","java.exe"):t?E.join(i,"jbr","Contents","Home","bin","java"):E.join(i,"jbr","bin","java"),sdkPath:s,hdcPath:E.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:E.join(o,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return se.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return se.existsSync(e)&&se.statSync(e).isDirectory()}catch{return!1}}static resolveInstallSource(){return n.installSourcePromise||(n.installSourcePromise=n.resolveInstallSourceUncached()),n.installSourcePromise}static async resolveInstallSourceUncached(){let e=[["DEVECO_CLI_STUDIO_PATH","studio","studio"],["DEVECO_CLI_CLT_PATH","clt","clt"],["DEVECO_HOME","studio","studio"],["DEVECO_PATH","studio","studio"]];for(let[r,i,o]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,i,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:o,toolchainRoot:a}}}let t=await Xd();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let i;try{i=po(e)}catch(o){throw new Error(`Invalid ${r}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}return t==="studio"&&Ze.platform()==="darwin"&&(i=n.normalizeMacStudioRoot(i)),n.isValidRoot(i,t)?i:n.throwInvalidSource(i,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let i=ct(e),o=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&o.push(["java",t.javaPath]);for(let[s,a]of o)n.assertInsideRoot(a,i,s)}static assertInsideRoot(e,t,r){if(uo(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,i){throw t==="clt"&&n.isValidRoot(e,"studio")?new Error(`${r} must point to Command Line Tools, not a DevEco Studio installation; use DEVECO_CLI_STUDIO_PATH instead`):t==="studio"&&n.isValidRoot(e,"clt")?new Error(`${r} must point to a DevEco Studio installation, not Command Line Tools; use DEVECO_CLI_CLT_PATH instead`):new Error(`Invalid ${r}: ${i}`)}static normalizeMacStudioRoot(e){let t=`${E.sep}Contents`,r=E.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return se.readFileSync(E.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(sw)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(E.join(t,"bin"))??n.javaIn(t)),i=(process.env.Path??process.env.PATH??"").split(E.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),o=r??i;if(o)return se.realpathSync(o);if(e)throw new Error("No Java runtime found in CLT mode. Set JAVA_HOME to a JDK/JBR installation directory (or point JAVA_HOME at the JDK bin directory), or add the JDK bin directory to PATH.");return""}static javaIn(e){return(Ze.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>E.join(e,r)).find(se.existsSync)}getMaxApiLevel(){for(let e of lw(this.sdkPath)){let t=cw(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Ze.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=E.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),i=E.join(r,"resources","apiChange"),o=E.join(r,"api-change-scan.js");if(!se.existsSync(i)||!se.existsSync(o)){let s=Wr(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${aw}. Upgrade before using 'check compat' at ${Va}`)}return this._apiscanPaths={apiChangeDir:i,scriptPath:o},this._apiscanPaths}static verifySignature(e){if(!se.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Ze.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&E.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!se.statSync(e).isFile())throw new Error;se.accessSync(e,se.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=E.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=se.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=E.join(E.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=`Get-AuthenticodeSignature -FilePath '${e.replace(/'/g,"''")}' | ConvertTo-Json -Depth 3 -Compress`;try{let i=nu(t,["-NoProfile","-ExecutionPolicy","Bypass","-Command",r],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),o=JSON.parse(i);return{signed:Number(o.Status)===0}}catch(i){return m(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!1}}}static verifyMacSignature(e){try{return nu("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as dw}from"execa";import*as jt from"path";import*as ho from"fs";import*as ru from"os";var Me=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let i=jt.dirname(e.javaPath),o=`${i}${jt.delimiter}${process.env.PATH||""}`,s={...process.env,PATH:o,DEVECO_SDK_HOME:e.sdkPath};e.sourceType==="clt"&&e.javaPath&&(s.JAVA_HOME=jt.dirname(i)),this.env=s}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,i){let o=[...Array.from(i),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(o)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){await this.runHvigor(["--stop-daemon"])}async ensureDaemonRunning(){if(this.findProjectDaemon()){m("[HvigorAdapter] Daemon already running.");return}m("[HvigorAdapter] No daemon running, starting via --sync --daemon (no hap build)."),await this.runHvigor(["--sync","--daemon"])}isDaemonRunning(e){return this.findProjectDaemon(e)!==null}findProjectDaemon(e){let t=this.getDaemonRegistryPath();if(!ho.existsSync(t))return null;try{let r=ho.readFileSync(t,"utf-8"),i=JSON.parse(r),o=e??this.projectRoot,s=Object.values(i).filter(a=>a.cwdPath===o&&(a.state==="idle"||a.state==="half_busy"||a.state==="busy")&&this.isProcessAlive(a.pid));return s.length>0?s[s.length-1]:null}catch{return null}}getDaemonRegistryPath(){let e=process.env.HVIGOR_USER_HOME||jt.join(ru.homedir(),".hvigor");return jt.join(e,"daemon","cache","daemon-sec.json")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}async compileNative(e,t){let r=["--mode","module"];t&&r.push("-p",`module=${t}`),r.push("-p",`product=${e}`,"compileNative","--analyze=normal"),await this.runHvigor(r)}async runHvigor(e){let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let i=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await dw(t,r,{cwd:this.projectRoot,env:this.env,stdout:i,stderr:i})}};import{execa as uw}from"execa";var Vn=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=[this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`),await uw(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as pw}from"fs/promises";import{dirname as fw,resolve as mw}from"path";import{execa as hw}from"execa";import{lock as za,check as BN}from"proper-lockfile";function qa(n){return mw(n,".hvigor",".build-lock")}function gw(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function iu(n){let e=fw(qa(n));if(await pw(e,{recursive:!0}),process.platform==="win32")try{await hw("attrib",["+h",e])}catch{}}async function yw(n,e){let t=new AbortController,r=gw(e);await iu(n);let i={lockfilePath:qa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await za(n,{...i,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await za(n,{...i,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Sn(n,e,t){let{release:r,signal:i}=await yw(n,t);try{return await e(i)}finally{await r()}}async function go(n,e){let t=new AbortController;await iu(n);let r={lockfilePath:qa(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},i;try{i=await za(n,{...r,retries:0})}catch(o){if(o&&typeof o=="object"&&"code"in o&&o.code==="ELOCKED")return{acquired:!1};throw o}try{return{acquired:!0,result:await e(t.signal)}}finally{await i()}}import*as Ht from"fs";import*as En from"path";import ww from"json5";var vw=1e3;function wo(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=En.join(n,Xe.SYNC_OUTPUT_PATH);if(!Ht.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=Ht.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Sw(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let i=En.join(n,Xe.OH_PACKAGE_JSON5),o=yo(i,t,"root");if(o.required)return m(`[ProjectCheck] Root check: ${o.reason}`),o;let s=En.join(n,Xe.BUILD_PROFILE_JSON5),a=yo(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=En.join(n,l.srcPath,Xe.OH_PACKAGE_JSON5),g=yo(d,t,l.name);if(g.required)return m(`[ProjectCheck] Module '${l.name}' check: ${g.reason}`),g;let w=En.join(n,l.srcPath,Xe.BUILD_PROFILE_JSON5),P=yo(w,t,l.name);if(P.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${P.reason}`),P}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function yo(n,e,t){if(!Ht.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=Ht.statSync(n).mtimeMs;return r-e>vw?{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 Sw(n){let e=En.join(n,Xe.BUILD_PROFILE_JSON5);try{let t=Ht.readFileSync(e,"utf-8");if(!t.trim())return null;let r=ww.parse(t);if(typeof r!="object"||r===null)return null;let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as xe from"fs";import*as Ut from"path";import*as vu from"util";import*as M from"fs";import*as ko from"path";import R from"fs";import*as vo from"os";import*as I from"path";import Ew from"json5";var Ya="Huawei";var au=3,cu=3,ou="DevEco Studio",lu={DevEcoStudio:"deveco_studio"};function So(n){if(!R.existsSync(n)||!R.statSync(n).isDirectory())return!1;let e=R.existsSync(I.join(n,"build-profile.json5")),t=R.existsSync(I.join(n,"hvigorfile.js"))||R.existsSync(I.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=R.readFileSync(I.join(n,"build-profile.json5"),"utf-8");return Ew.parse(r).app!==void 0}catch{return!1}}function Ja(n,e,t){if(e>=t)return null;let r=bw(n),i=Pw(r);if(i)return i;for(let o of r){let s=Ja(o,e+1,t);if(s)return s}return null}function bw(n){try{let e=R.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(I.join(n,r.name));return t}catch{return[]}}function Pw(n){for(let e of n)if(So(e))return e;return null}function vt(n){if(!n||n.trim()==="")return null;let e=I.resolve(n),t;try{t=R.realpathSync(e)}catch{t=e}if(!R.existsSync(t))return null;if(So(t))return t;let r=t;for(let i=1;i<=3;i++){let o=I.dirname(r);if(o===r)break;if(So(o))return o;r=o}if(R.statSync(t).isDirectory()){let i=Ja(t,0,au);if(i)return i}return null}function Eo(n){if(!n||n.trim()==="")return null;let e=I.resolve(n),t;try{t=R.realpathSync(e)}catch{t=e}return!R.existsSync(t)||!R.statSync(t).isDirectory()?null:So(t)?t:Ja(t,0,au)}function Cw(n){let e=n??Xa();if(!e)return null;let t=null;if(process.platform==="win32"?t=I.join(e,"plugins","openharmony"):process.platform==="darwin"&&(t=I.join(e,"contents","plugins","openharmony")),t){let o=I.join(t,"ace-server","out","index.js");if(R.existsSync(o))return t}let r=I.join(e,"arkts-lsp","lib"),i=I.join(r,"out","index.js");return R.existsSync(i)?r:null}function Ka(n){let e=Rw(n??""),t=I.join(e,"sdk");return R.existsSync(t)?t:I.join(du(e),"sdk")}function bo(n){let e=I.dirname(n),t=[I.join(e,"tools","hvigor","bin","hvigorw.js"),I.join(e,"hvigor","bin","hvigorw.js")];for(let r of t)if(R.existsSync(r))return r;return null}function Po(n){return{sdkPath:Ka(n),arktsLangServerPath:Cw(n)}}function zr(n,e){let t=e?I.join("standardIndex","index.js"):"index.js";return R.existsSync(I.join(n,"ace-server"))?I.join(n,"ace-server","out",t):I.join(n,"out",t)}function Co(n){return R.existsSync(zr(n,!0))}var Iw=["default","openharmony","native","llvm","bin","clangd"],Aw=[".idea",".deveco","cxx","compile_commands.json"];function Io(n){let e=I.join(n,...Iw),t=process.platform==="win32"?e+".exe":e;return R.existsSync(t)?t:null}function qr(n){return I.join(n,...Aw)}function Xa(){if(process.platform==="win32"){let n=[I.join("C:\\Program Files",Ya,ou),I.join("C:\\Program Files (x86)",Ya,ou)];return su(n)}if(process.platform==="darwin"){let n=["/Applications/DevEco Studio.app",I.join(process.env.HOME??"","Applications","DevEco Studio.app")];return su(n)}return null}function su(n){for(let e of n)if(R.existsSync(e))return e;return null}function du(n){return process.platform==="darwin"?I.join(n,"Contents"):n}function Dw(n){if(!n||!R.existsSync(n)||!uu(n))return!1;let e=du(n);return[I.join(e,"plugins","openharmony"),I.join(e,"sdk"),I.join(e,"tools")].some(r=>R.existsSync(r))}function uu(n){try{return R.statSync(n).isDirectory()}catch{return!1}}function Za(n,e){return!n||!R.existsSync(n)?!1:e===lu.DevEcoStudio?Dw(n):!1}function Rw(n,e=lu.DevEcoStudio){if(!n)return"";if(Za(n,e))return n;let t=kw(n,e);if(t)return t;let r=Tw(n,e);return r||n}function kw(n,e){let t=n;for(let r=0;r<cu;r++){let i=I.dirname(t);if(!i||i===t)break;if(Za(i,e))return i;t=i}return null}function Tw(n,e){if(!R.existsSync(n)||!uu(n))return null;let t=[{p:n,depth:0}];for(;t.length>0;){let{p:r,depth:i}=t.shift();if(i>=cu)continue;let o=xw(r,i,e,t);if(o)return o}return null}function xw(n,e,t,r){let i;try{i=R.readdirSync(n,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=I.join(n,o.name);if(Za(s,t))return s;r.push({p:s,depth:e+1})}return null}function pu(n){return new Promise(e=>setTimeout(e,n))}var Nw=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function bn(n){let e=I.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Nw.has(e)}function Ao(n){return I.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ae(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Lw(n){return ae(n)}function Pn(n){let e=Lw(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function $t(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??I.join(vo.homedir(),"AppData","Local");return I.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?I.join(vo.homedir(),"Library","Logs","devecocli-mcp-server"):I.join(vo.homedir(),".local","share","devecocli-mcp-server","logs")}function fu(n,e){let t=Ow(e),r=Mw(t,n);if(r!==null)return r;let i=Date.now(),s=`${n.replace(/:/g,"\\:")}=${i}`,a=_w(t,n,s);return Fw(e,a),i}function Ow(n){let e;try{e=R.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Mw(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(r+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function _w(n,e,t){let r=!1,i=n.map(o=>{if(r)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):o});return r||i.push(t),i}function Fw(n,e){try{R.mkdirSync(I.dirname(n),{recursive:!0})}catch{}try{R.writeFileSync(n,e.join(`
|
|
9
9
|
`)+`
|
|
10
|
-
`,"utf8")}catch{}}function
|
|
11
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);M.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{M.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},
|
|
10
|
+
`,"utf8")}catch{}}function Qa(n,e,t="[Cleanup]"){try{let r=I.dirname(n);if(!R.existsSync(r))return;let i=Date.now();for(let o of R.readdirSync(r,{withFileTypes:!0}))o.isDirectory()&&jw(I.join(r,o.name),i,e,t)}catch{}}function jw(n,e,t,r){try{let{mtimeMs:i}=R.statSync(n);if(e-i<=t)return;R.rmSync(n,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${n}`)}catch(i){console.error(`${r} Failed to remove expired dir ${n}: ${i}`)}}function Do(n){let e=n.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",r=I.join(e,"node",t);return R.existsSync(r)||process.platform!=="win32"&&(r=I.join(e,"node","bin","node"),R.existsSync(r))?r:process.execPath??"node"}var mu="mcp-server.log",Hw="mcp-server",$w={maxSize:10*1024*1024,maxFiles:4},ec=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={...$w,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=$t(),this.currentLogFile=ko.join(this.logDir,mu),M.existsSync(this.logDir)||M.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${i}`}getRotatedFileName(e,t){return ko.join(this.logDir,`${Hw}-${e}.log.${t}`)}fileExists(e){try{return M.accessSync(e,M.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=M.readdirSync(this.logDir),t=[];for(let i of e)if(i===mu||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=ko.join(this.logDir,i),s=M.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let i=r;i<t.length;i++)try{M.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&M.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&M.renameSync(o,s)}let r=this.getRotatedFileName(e,1);M.renameSync(this.currentLogFile,r),this.cleanupOrphanLogFiles(),this.openLogFile()}catch{this.openLogFile()}finally{this.isRotating=!1}}}openLogFile(){if(this.currentLogFile){this.currentDate=this.getCurrentDateString();try{if(this.fileExists(this.currentLogFile)){let e=M.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=M.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{M.closeSync(this.fd)}catch{}this.fd=null}}checkRotation(e){let t=this.getCurrentDateString();this.currentDate&&this.currentDate!==t&&(this.rotateLog(),this.currentDate=t),this.currentFileSize+=e,this.currentFileSize>=this.rotationOptions.maxSize&&this.rotateLog()}write(e,t,...r){if(this.mode==="silent"||n.LEVEL_ORDER[e]<n.LEVEL_ORDER[this.minLevel])return;let i=r.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
|
|
11
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);M.writeSync(this.fd,c),this.checkRotation(c.byteLength)}catch{this.closeLogFile(),this.openLogFile()}}else this.mode==="console"&&process.stderr.write(a)}debug(e,...t){this.write("debug",e,...t)}info(e,...t){this.write("info",e,...t)}warn(e,...t){this.write("warn",e,...t)}error(e,...t){this.write("error",e,...t)}dispose(){this.closeLogFile()}flush(){if(!(this.mode!=="file"||this.fd===null))try{M.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},_e=null;function Cn(n=!1){_e&&_e.dispose(),_e=new ec(n)}function hu(){_e&&(_e.dispose(),_e=null)}function gu(){_e&&_e.flush()}function yu(){return _e?.getLogFilePath()??null}function wu(){return _e?.getLogDirectory()??null}function Ro(){return _e||Cn(!1),_e}var h={debug:(n,...e)=>Ro().debug(n,...e),info:(n,...e)=>Ro().info(n,...e),warn:(n,...e)=>Ro().warn(n,...e),error:(n,...e)=>Ro().error(n,...e)};var tc="";function xo(n){if(!n||n==="auto"||n==="stdout"||n==="none"){tc="";return}tc=n}function Su(){return tc||(wu()??"")}function To(n,...e){if(e.length===0)return n;try{return vu.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){h.info(`[lsp] ${To(n,...e)}`)},warn(n,...e){h.warn(`[lsp] ${To(n,...e)}`)},error(n,...e){h.error(`[lsp] ${To(n,...e)}`)},debug(n,...e){h.debug(`[lsp] ${To(n,...e)}`)}};import*as Yr from"fs";import*as Jr from"os";import*as zn from"path";import Uw from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},k="2.0";var Eu=8192,nc=100,bu=.03,Pu=.7,Fe=900*1e3;function Te(n){if(!Yr.existsSync(n))return null;try{let e=Yr.readFileSync(n,"utf-8");return e.trim()?Uw.parse(e):null}catch{return null}}function No(n,e){let t=Math.floor(Jr.totalmem()/1048576),r=Math.floor(t*Pu),i,o;e!==void 0&&Number.isFinite(e)&&e>0?(i=e,o=`override(${e})`):(i=Eu,n>nc&&(i+=(n-nc)*bu*1024),o=`formula(moduleCount=${n})`);let s=r>0&&i>r;s&&(i=r);let a=Math.round(i);return f.info(`[computeLspServerMaxSize] source=${o}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function Qe(n){if(n.startsWith("file:"))return n;try{let e=zn.resolve(n),t=new URL(`file://${e}`).toString();if(Jr.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let i=r[1].toUpperCase(),o=t.substring(`file:///${r[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return n}}function qn(n){return n&&n.replace(/\\/g,"/")}function U(n){let e=zn.normalize(n).replace(/\\/g,"/");if(Jr.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Cu(n){return zn.join(n,"build-profile.json5")}var St=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Cu(this.projectRoot);try{let t=Te(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import{spawn as Bw}from"child_process";import*as Oo from"fs";var Ww=600*1e3;function Gw(n,e,t){let r=t.split(/\s+/).filter(i=>i.length>0);return[n,[e,...r]]}function Vw(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{let i=r.toString();t.push(i),i.split(/\r?\n/).filter(Boolean).forEach(o=>f.info("[hvigor:err] %s",o))}),{stdout:e,stderr:t}}function Lo(n){return n.join("")}function zw(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
12
12
|
Output so far:
|
|
13
|
-
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function
|
|
13
|
+
`+t,exitCode:-1};let r=n??-1;return{success:r===0,output:t,exitCode:r}}function qw(n,e,t){return new Promise(r=>{let i=Bw(n[0],n[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=Vw(i),a=setTimeout(()=>{i.kill();let c=[Lo(o),Lo(s)].filter(Boolean).join(`
|
|
14
14
|
`).trim();r({success:!1,output:`Build process timeout after 10 minutes.
|
|
15
15
|
Output so far:
|
|
16
|
-
`+c,exitCode:-1})},
|
|
17
|
-
`).trim()||"";r(
|
|
16
|
+
`+c,exitCode:-1})},Ww);i.on("close",(c,l)=>{clearTimeout(a);let d=[Lo(o),Lo(s)].filter(Boolean).join(`
|
|
17
|
+
`).trim()||"";r(zw(c,l,d))}),i.on("error",c=>{clearTimeout(a),r({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function rc(n,e,t,r,i){let o={...process.env,DEVECO_SDK_HOME:r},s=Gw(e,t,i);return await qw(s,n,o)}function Yw(n){let e=bo(n)??"";return{node_path:Do(n),hvigor_path:e,sdk_path:n}}function Jw(n){return!n.node_path||!Oo.existsSync(n.node_path)?`Node path not found or invalid: ${n.node_path}`:!n.hvigor_path||!Oo.existsSync(n.hvigor_path)?`Hvigor path not found or invalid: ${n.hvigor_path}`:!n.sdk_path||!Oo.existsSync(n.sdk_path)?`SDK path not found or invalid: ${n.sdk_path}`:null}var Kw="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Iu(n,e){try{let t=Yw(e),r=Jw(t);if(r!=null)return f.info(`Config validation failed: ${r}`),!1;let i=await rc(n,t.node_path,t.hvigor_path,e,Kw);return f.info(`[hvigor] sync finished: success=${i.success}, exitCode=${i.exitCode}`),i.success}catch(t){return f.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}function Xw(n){let e=Ut.extname(n).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function Zw(n,e){let t=Ut.join(n,e.name);return e.isDirectory()?e.name===".cxx"||Au(t):Xw(t)}function Au(n){if(!xe.existsSync(n))return!1;try{return xe.readdirSync(n,{withFileTypes:!0}).some(t=>Zw(n,t))}catch{}return!1}function In(n){let t=new St(n).getAllModuleInfo(),r=[];for(let i of t){let o=v.resolvePathWithinRoot(n,i.srcPath);Au(o)&&r.push(i)}return r}function Qw(n){let e=[],r=new St(n).getAllModuleInfo();for(let i of r){let o=v.resolvePathWithinRoot(n,i.srcPath),s=Ut.join(o,".cxx");xe.existsSync(s)&&Du(s,e)}return e}function Du(n,e){try{let t=xe.readdirSync(n,{withFileTypes:!0});for(let r of t){let i=Ut.join(n,r.name);r.isDirectory()?Du(i,e):r.name==="compile_commands.json"&&e.push(i)}}catch{}}function ev(n){let e=[];for(let t of n)try{let r=xe.readFileSync(t,"utf8"),i=JSON.parse(r);e.push(...i)}catch{}return e}function tv(n,e){let t=Ut.join(n,...nv.slice(0,-1));xe.mkdirSync(t,{recursive:!0});let r=Ut.join(t,"compile_commands.json");xe.writeFileSync(r,JSON.stringify(e,null,2),"utf8")}function ic(n){let e=Qw(n);if(e.length>0){let t=ev(e);tv(n,t),h.info(`[CppCompile] compile_commands.json generated, ${t.length} compile commands`)}else h.warn("[CppCompile] No compile_commands.json files found")}var nv=[".idea",".deveco","cxx","compile_commands.json"];async function rv(n,e,t){let r=bo(e);if(!r){h.warn(`[CppCompile] hvigorw.js not found under sdk '${e}'`);return}let i=process.execPath||"node";h.info(`[CppCompile] sdkPath: ${e}, hvigorPath: ${r}`);for(let o of t){let s=["--mode","module","-p",`module=${o.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");h.info(`[CppCompile] Running compileNative for module: ${o.name}`);let a=await rc(n,i,r,e,s);a.success?h.info(`[CppCompile] compileNative ${o.name} succeeded`):h.warn(`[CppCompile] compileNative ${o.name} failed: ${a.output}`)}}async function Ru(n,e){let t=In(n);if(t.length===0){h.info("[CppCompile] No C++ modules found, skipping initialization");return}h.info(`[CppCompile] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),await rv(n,e,t),ic(n)}function ov(n,e){if(e.product&&n.validateProduct(e.product),e.buildMode){let t=["debug","release"],r=(n.profile.app.buildModeSet?.map(o=>o.name)??[]).filter(o=>!t.includes(o)),i=[...t,...r];if(!i.includes(e.buildMode))throw new Error(`Build mode '${e.buildMode}' not found. Available modes: ${i.join(", ")}`)}}function sv(n,e){let t=n.profile.modules.map(i=>i.name),r=new Set(t);for(let i of e){let o=i.split("@",1)[0];if(!r.has(o))throw new Error(`Module '${o}' not found in project-level build-profile.json5. Available modules: ${t.join(", ")||"none"}`)}}function av(n,e){let t;if(e.modules&&e.modules.length>0)t=e.modules,sv(n,t);else{let i=n.profile.modules,o=i.filter(s=>n.getModuleType(s.name)==="entry");if(i.length===1)t=[i[0].name];else if(o.length===1)t=[o[0].name];else throw o.length>1?new Error(`Multiple entry modules found (${o.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`):new Error(`No entry module found and multiple modules available (${i.map(s=>s.name).join(", ")}). Please specify which module to build with --modules.`)}let r=new Set;for(let i of t){let o=i.indexOf("@"),s=o!==-1?i.substring(0,o):i,a=o!==-1?i.substring(o+1):"default";r.add(`${s}@${a}`)}return Array.from(r)}function cc(n,e){let t=new Set;for(let r of e){let i=r.indexOf("@"),o=i!==-1?r.substring(0,i):r,s=n.getModuleType(o);s==="shared"?t.add("assembleHsp"):s==="har"?t.add("assembleHar"):t.add("assembleHap")}return t}function Kr(n,e){let t=e,r=`${n} failed`;console.error(sc(r));let i=t.stdout||t.message;throw i&&console.error(i),t.stderr&&console.error(t.stderr),new Error(r,{cause:e})}async function lc(n,e,t,r,i,o){let s=wo(o);console.log(`
|
|
18
18
|
[ohpm install] Running...`);try{await n.installAll()}catch(a){Kr("ohpm install",a)}if(s.required){console.log(`
|
|
19
19
|
[hvigor sync] Running...`);try{await e.sync(t,r)}catch(a){Kr("hvigor sync",a)}}else console.log(`
|
|
20
20
|
[hvigor sync] Skipped (configurations unchanged)`);console.log(`
|
|
21
|
-
[hvigor build] Running...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){Kr("hvigor build",a)}
|
|
22
|
-
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(
|
|
23
|
-
Failed to merge compile_commands.json: ${e.message}`))}}var
|
|
24
|
-
`+
|
|
21
|
+
[hvigor build] Running...`);try{i.type==="product"?await e.buildProduct(t,r):await e.buildModules(t,r,i.modulesToBuild,i.moduleTasks)}catch(a){Kr("hvigor build",a)}cv(o)}function cv(n){try{if(In(n).length===0)return;ic(n),console.log(oc(`
|
|
22
|
+
Merged central compile_commands.json for C++ language server.`))}catch(e){console.warn(ac(`
|
|
23
|
+
Failed to merge compile_commands.json: ${e.message}`))}}var ku=new iv("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=V.discover(e);console.warn(ac("Ensure the project source is trustworthy before proceeding.")),ov(t,n);let r=n.product||"default",i=n.buildMode||"debug",o;if(n.product&&!n.modules)o={type:"product"};else{let l=av(t,n),d=cc(t,l);o={type:"modules",modulesToBuild:l,moduleTasks:d}}let s=await A.new();s.assertJava();let a=new Vn(s,t.rootDir),c=new Me(s,t.rootDir);await Sn(t.rootDir,async()=>lc(a,c,r,i,o,t.rootDir),()=>{console.log("Another build is already running for this project. Waiting for completion...")}),console.log(`
|
|
24
|
+
`+oc("Build completed successfully"))}catch(e){console.error(sc(e.message)),process.exit(1)}});ku.command("clean").description("Clean HarmonyOS project build outputs").action(async()=>{try{let n=process.cwd(),e=V.discover(n);console.warn(ac("Ensure the project source is trusted before proceeding."));let t=await A.new();t.assertJava();let r=new Me(t,e.rootDir);await Sn(e.rootDir,async()=>{console.log(`
|
|
25
25
|
[1/2] Running hvigor clean...`);try{await r.clean()}catch(i){Kr("hvigor clean",i)}console.log(`
|
|
26
26
|
[2/2] Running hvigor --stop-daemon...`);try{await r.stopDaemon()}catch(i){Kr("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
27
|
-
`+
|
|
27
|
+
`+oc("Clean completed successfully."))}catch(n){console.error(sc(n.message)),process.exit(1)}});var Tu=ku;import{Command as qv}from"commander";import{green as ei,red as Yv,yellow as Wo}from"colorette";import*as Go from"path";import{randomUUID as Ev}from"crypto";import{execa as bv}from"execa";import{execa as Sv}from"execa";import{execFile as lv,spawn as dv}from"child_process";import{promisify as uv}from"util";var pv=uv(lv);function xu(n,e,t){let i=n.replace(/\r\n/g,`
|
|
28
28
|
`).split(`
|
|
29
|
-
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function
|
|
30
|
-
`)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Jn(this.hdcPath,e,[...
|
|
29
|
+
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function Nu(n,e,t){let r=n.endsWith("\r")?n.slice(0,-1):n;r.length>0&&t.onData([r],e)}function fv(n,e){return{stdout:n.stdoutChunks.join(""),stderr:n.stderrChunks.join(""),exitCode:e??-1}}function mv(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function hv(n,e,t,r,i){n.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=xu(e.stdoutLineBuffer+s,"stdout",t)}),n.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=xu(e.stderrLineBuffer+s,"stderr",t)}),n.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),n.on("close",o=>{if(e.settled)return;e.settled=!0,Nu(e.stdoutLineBuffer,"stdout",t),Nu(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=fv(e,o);r(s)})}async function Xr(n,e=[],t={}){try{let{stdout:r,stderr:i}=await pv(n,e,t);return{stdout:typeof r=="string"?r.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(r){let i=r;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function Lu(n,e,t){return await new Promise((r,i)=>{let o=dv(n,e,{stdio:["inherit","pipe","pipe"]}),s=mv();hv(o,s,t,r,i)})}function Ou(n){let e=n.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var gv=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i,/not connected/i],yv=[/\[fail\]/i,/\bfail!/i,/not found/i,/permission denied/i,/device unauthorized/i];function Yn(n){return n?gv.some(e=>e.test(n))?"transient":yv.some(e=>e.test(n))?"fatal":"ok":"ok"}var dc=[800,1500,2500];function wv(n){return new Promise(e=>setTimeout(e,n))}async function X(n,e){let t=1+dc.length,r={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){if(r=await Xr(n,e),r.exitCode===0||Yn(r.stderr)!=="transient"||i>=t-1)return r;m(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${dc[i]}ms`),await wv(dc[i])}return r}var Mu=/^[\w.-]+$/;async function Mo(n,e,t){if(!Mu.test(t)){m(`Skipping invalid param key: ${JSON.stringify(t)}`);return}let r=["-t",e,"shell","param","get",t];m(`Executing: ${n} ${r.join(" ")}`);let i=await X(n,r);if(i.exitCode!==0)return;let o=i.stdout.trim();if(!(!o||Yn(o)!=="ok"))return Ou(o)}var uc="__DEVECO_PARAM_DELIM__";function vv(n,e){let t=new Map,r=n.split(uc);for(let i=0;i<e.length;i++){let o=(r[i]??"").trim();if(!o||Yn(o)!=="ok")continue;let s=Ou(o);s&&t.set(e[i],s)}return t}async function Jn(n,e,t){let r=t.filter(a=>Mu.test(a)?!0:(m(`Skipping invalid param key: ${JSON.stringify(a)}`),!1));if(r.length===0)return new Map;if(r.length===1){let a=new Map,c=await Mo(n,e,r[0]);return c&&a.set(r[0],c),a}let i=r.map(a=>`param get ${a}`).join(`; echo ${uc}; `)+`; echo ${uc}`,o=await X(n,["-t",e,"shell",i]);if(o.exitCode===0){let a=vv(o.stdout,r);if(a.size>0)return a}m(`Batched param fetch failed (exit=${o.exitCode}), falling back to individual calls for ${e}`);let s=new Map;for(let a of r){let c=await Mo(n,e,a);c&&s.set(a,c)}return s}function Bt(n){return n.startsWith("127.0.0.1:")}var _u=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype","const.build.product"],Z=class n{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new n(e.hdcPath)}static withHdcPath(e){return new n(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let r=e.trim(),i=t?.trim();if(!r||!i)return r;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return r.replace(o,"").trim()||r}async executeHdc(e){return m(`Executing: ${this.hdcPath} ${e.join(" ")}`),Sv(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let r of e.split(`
|
|
30
|
+
`)){let i=r.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];if(!s||s.startsWith("[Empty]"))continue;let a=o.length>=2?o[1]:"device";if(a.toLowerCase()==="unauthorized"){m(`[DeviceManager] Skipping unauthorized device: ${s}`);continue}t.push({serial:s,status:a})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let r=e.get("const.product.name");if(r&&r!=="emulator")return r;let i=e.get("const.product.model");if(i&&i!=="emulator"){let s=e.get("const.product.brand");return this.stripBrandPrefix(i,s)}let o=e.get("const.build.product");if(o&&o!=="emulator")return o}async getDeviceName(e){let t=await Jn(this.hdcPath,e,[..._u]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let r=e.find(s=>s.serial===t);if(r)return r;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase()===i&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Use a serial instead:
|
|
31
31
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
32
|
-
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Jn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Bt(e),r,i;try{let o=await Jn(this.hdcPath,e,[...Mu]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Wt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await yv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${gv()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import uc from"fs";import*as An from"path";function Zr(n,e){if(!uc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=uc.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=An.resolve(e),o=new Set,s=[];for(let a of r){let c=An.resolve(i,a),l=An.isAbsolute(a)?An.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=E.isPathContainedWithSymlink(l,i);if(!d.contained){if(!uc.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import pc from"fs";import Qr from"path";import{execa as Sv}from"execa";import _u from"fs";import*as Fu from"path";import wv from"json5";function vv(n,e){try{let r=wv.parse(_u.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function dt(n,e){let t=Fu.join(n,"build-profile.json5");return _u.existsSync(t)?vv(t,e)??e:e}async function ju(n,e,t,r){let i=Qr.dirname(n.javaPath),o={...process.env,PATH:`${i}${Qr.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Sv(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>bv(e,l,r))}function Hu(n,e,t){let r=dt(n,e);return Qr.join(n,r,"build",t,"outputs")}function Ev(n,e,t){return Qr.join(Hu(n,e,t),`${e}-${t}-signed.hqf`)}function bv(n,e,t){let r=Hu(n,e,t),i=Ev(n,e,t);if(pc.existsSync(i))return i;let o=fc(r,"-signed.hqf")??fc(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function fc(n,e){if(!pc.existsSync(n))return null;for(let t of pc.readdirSync(n,{withFileTypes:!0})){let r=Qr.join(n,t.name);if(t.isDirectory()){let i=fc(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import z from"fs";import*as x from"path";import mc from"json5";var $u="default",Kn=class n{static writeChangedFileLists(e,t,r,i){let o=t||$u,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||$u,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=x.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0}static initEmptyForModule(e,t,r,i){let o=x.join(e,r,"build",t,"intermediates","patch","default"),s=x.join(o,"changedFileList.json");if(z.existsSync(s)||(z.mkdirSync(o,{recursive:!0}),z.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=x.join(e,r,"build",t,"intermediates","hotReload"),c=x.join(a,"changedFileList.json");z.existsSync(c)||(z.mkdirSync(a,{recursive:!0}),z.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!z.existsSync(t))return null;try{let r=z.readFileSync(t,"utf-8");return mc.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=x.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=x.normalize(e);for(let o of r){let s=x.normalize(x.join(t,o.srcPath)),a=s+x.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=x.join(e,t,"src","main","module.json5");if(!z.existsSync(r))return"entry";try{let i=z.readFileSync(r,"utf-8");return mc.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=x.join(e,t,"oh-package.json5");if(!z.existsSync(r))return[];try{let i=z.readFileSync(r,"utf-8"),o=mc.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=x.resolve(e,t,o);return i.find(l=>x.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=x.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"&&e.patchResFiles.push({filePath:t,resourcePath:s})}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=x.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=x.dirname(s);z.existsSync(l)||z.mkdirSync(l,{recursive:!0}),z.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!z.existsSync(e))return[];try{let t=z.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=x.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=x.join(e,a,"src","main","ets"),g=i.map(wt=>n.resolveRelativePathForPatch(wt,d)),w=n.mergeStrings(l.modifiedFiles,g),P=n.mergePatchResources(l.rawFile,o),O=n.mergePatchResources(l.resFile,s),ne=x.dirname(c);z.existsSync(ne)||z.mkdirSync(ne,{recursive:!0}),z.writeFileSync(c,JSON.stringify({resources:{resFile:O,rawFile:P},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!z.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=z.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return x.relative(x.normalize(t),x.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import Pv from"fs";import{randomUUID as Cv}from"crypto";import{execa as Iv}from"execa";var Xn=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r,i=!1){for(let c of t)if(!Pv.existsSync(c)){let l=`Signed hqf file not found: ${c}`;return console.error(`[Apply] ${l}`),{success:!1,message:l}}let s=`/data/local/tmp/${Cv()}`,a=[];try{for(let c=0;c<t.length;c++){let l=`${s}/${r}_${c}.hqf`;a.push(l),await this.pushHqf(e,t[c],s,l)}return await this.executeQuickfix(e,a,i)}catch(c){let l=`hqf install error: ${c.message}`;return console.error(`[Apply] ${l}`),{success:!1,message:l}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",s],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t,r=!1){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let i=["-t",e,"shell","bm","quickfix","-a","-f",...t];r||i.push("-o");let o=await this.runHdc(i,!1);if(m(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Iv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var Av="6.1.1",_o=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Sn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(Av);let t=Zr(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),i=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Kn.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await ju(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Xn(this.toolProvider).install(e.targetDeviceId,t,e.bundleName,e.isHotReload??!1);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Wt(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new Wt(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){console.warn(`[Apply] launch app failed: ${r.message}`)}}};import Uu from"fs";import*as F from"path";var Fo=class n{static generate(e,t,r,i){let o=dt(e,t),s=F.join(e,o),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Uu.mkdirSync(a,{recursive:!0}),Uu.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=F.dirname(i.nodePath)+F.sep,s=F.join(t,"build",r),a=F.join(s,"intermediates"),c=F.join(a,"loader_out",r),l=F.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:F.join(e,"build-profile.json5"),localPropertiesPath:F.join(e,"local.properties"),appResource:F.join(l,"ResourceTable.txt"),cachePath:F.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:F.join(a,"loader",r,"loader.json"),aceModuleJsonPath:F.join(l,"module.json"),aceSoPath:F.join(c,"nativeDependencies.txt"),aceModuleRoot:F.join(t,"src","main","ets"),aceModuleBuild:F.join(c,"ets"),aceProfilePath:F.join(l,"resources","base","profile"),aceSuperVisualPath:F.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:F.join(c,"ets"),changedFileList:F.join(a,"patch","default","changedFileList.json"),patchAbcPath:F.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import Bu from"fs";import*as j from"path";var jo=class n{static generate(e,t,r,i){let o=dt(e,t),s=j.join(e,o),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Bu.mkdirSync(a,{recursive:!0}),Bu.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=j.dirname(i.nodePath)+j.sep,s=j.join(t,"build",r),a=j.join(s,"intermediates"),c=j.join(a,"loader_out",r),l=j.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:j.join(e,"build-profile.json5"),localPropertiesPath:j.join(e,"local.properties"),appResource:j.join(l,"ResourceTable.txt"),cachePath:j.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:j.join(a,"loader",r,"loader.json"),aceModuleJsonPath:j.join(l,"module.json"),aceSoPath:j.join(c,"nativeDependencies.txt"),aceModuleRoot:j.join(t,"src","main","ets"),aceModuleBuild:j.join(c,"ets"),aceProfilePath:j.join(l,"resources","base","profile"),aceSuperVisualPath:j.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:j.join(c,"ets"),changedFileList:j.join(a,"hotReload","changedFileList.json"),patchAbcPath:j.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Wu from"crypto";import je from"fs";import He from"path";import Gu from"os";import{io as Dv}from"socket.io-client";var Rv=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Zn=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;je.mkdirSync(He.dirname(i),{recursive:!0}),je.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
32
|
+
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let r=await Jn(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=r.get("const.product.devicetype");let i=r.get("const.ohos.apiversion"),o=r.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=Bt(e),r,i;try{let o=await Jn(this.hdcPath,e,[..._u]);r=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:r,isEmulator:t,deviceType:i}}};var Wt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Z.from(e)}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await bv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let r=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(r.includes("uninstall bundle successfully"))return!0;if(r.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${r}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${Ev()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,r){let i=["-t",e,"shell","aa","start","-a",r,"-b",t];return await this.runHdc(i)}async forceStopApp(e,t){let r=["-t",e,"shell","aa","force-stop",t];return await this.runHdc(r,!1)}};import pc from"fs";import*as An from"path";function Zr(n,e){if(!pc.existsSync(n))throw new Error(`Apply file list not found: ${n}`);let r=pc.readFileSync(n,"utf-8").split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0&&!a.startsWith("#"));if(r.length===0)throw new Error("Apply file list is empty (no valid entries)");let i=An.resolve(e),o=new Set,s=[];for(let a of r){let c=An.resolve(i,a),l=An.isAbsolute(a)?An.relative(i,a):a;if(l.startsWith(".."))throw new Error(`File path is outside the project directory: ${a}`);let d=v.isPathContainedWithSymlink(l,i);if(!d.contained){if(!pc.existsSync(c))throw new Error(`File not found: ${a}`);let g=d.reason?`; ${d.reason}`:"";throw new Error(`File path is outside the project directory: ${a}${g}`)}o.has(c)||(o.add(c),s.push(c))}return s}import fc from"fs";import Qr from"path";import{execa as Iv}from"execa";import Fu from"fs";import*as ju from"path";import Pv from"json5";function Cv(n,e){try{let r=Pv.parse(Fu.readFileSync(n,"utf-8")).modules?.find(i=>i.name===e);return r?.srcPath?r.srcPath.replace(/^\.\//,""):null}catch(t){return m(`[apply] resolveModuleSrcPath fallback (module=${e}): ${t.message}`),null}}function dt(n,e){let t=ju.join(n,"build-profile.json5");return Fu.existsSync(t)?Cv(t,e)??e:e}async function Hu(n,e,t,r){let i=Qr.dirname(n.javaPath),o={...process.env,PATH:`${i}${Qr.delimiter}${process.env.PATH||""}`,DEVECO_SDK_HOME:n.sdkPath},s=[n.hvigorJsPath,"--mode","module","-p",`module=${t.join(",")}@${r}`,"-p",`product=${r}`,"-p","debuggable=true","assembleDevHqf","--analyze=normal","--parallel","--incremental","--no-daemon"];m(`[buildSignedHqf] ${n.nodePath} ${s.join(" ")}`);let a=await Iv(n.nodePath,s,{cwd:e,env:o,stdout:"inherit",stderr:"inherit",reject:!1}),c=(a.exitCode??0)|0;if(c===-1)throw new Error("hvigor hot compile produced invalid abc (exit code -1)");if(c!==0)throw new Error(`hvigor assembleDevHqf failed with exit code ${a.exitCode}`);return t.map(l=>Dv(e,l,r))}function $u(n,e,t){let r=dt(n,e);return Qr.join(n,r,"build",t,"outputs")}function Av(n,e,t){return Qr.join($u(n,e,t),`${e}-${t}-signed.hqf`)}function Dv(n,e,t){let r=$u(n,e,t),i=Av(n,e,t);if(fc.existsSync(i))return i;let o=mc(r,"-signed.hqf")??mc(r,".hqf");if(!o)throw new Error(`Signed hqf not found at ${i} (and no *.hqf under ${r})`);return m(`[buildSignedHqf] signed hqf not at exact path, using fallback: ${o}`),o}function mc(n,e){if(!fc.existsSync(n))return null;for(let t of fc.readdirSync(n,{withFileTypes:!0})){let r=Qr.join(n,t.name);if(t.isDirectory()){let i=mc(r,e);if(i)return i}else if(t.isFile()&&t.name.endsWith(e))return r}return null}import z from"fs";import*as x from"path";import hc from"json5";var Uu="default",Kn=class n{static writeChangedFileLists(e,t,r,i){let o=t||Uu,s=n.loadBuildProfile(e);if(!s)return{writtenModules:[],skippedFiles:r};let a=s.modules,c=n.filterRunnableModules(e,a);if(c.length===0)return{writtenModules:[],skippedFiles:r};let l=n.buildReverseDependencyMap(e,a),d=n.createCollectors(c),g=n.collectChanges(r,e,a,l,d);return{writtenModules:n.flushCollectors(e,o,c,d,i),skippedFiles:g}}static initEmptyChangedFileLists(e,t,r){let i=t||Uu,o=n.loadBuildProfile(e);if(!o)return[];let s=o.modules,a=[];for(let c of s){let l=n.getModuleType(e,c.srcPath);if(l!=="entry"&&l!=="shared")continue;let d=!r||c.name===r;n.initEmptyForModule(e,i,c.srcPath,d),a.push(c.name)}return a}static filterRunnableModules(e,t){return t.filter(r=>{let i=n.getModuleType(e,r.srcPath);return i==="entry"||i==="shared"})}static createCollectors(e){let t=new Map;for(let r of e)t.set(r.name,{hotReloadEntries:[],patchEtsFiles:[],patchRawFiles:[],patchResFiles:[],nativeFiles:[]});return t}static collectChanges(e,t,r,i,o){let s=[];for(let a of e){let c=x.normalize(a),l=n.classifyFile(c,t,r);if(l.fileClass==="unknown"){s.push(c);continue}let d=n.findModuleByFilePath(c,t,r);if(!d){s.push(c);continue}let g=n.resolveTargetModules(d,t,r,i);if(g.length===0){s.push(c);continue}n.dispatchToCollectors(g,o,c,l,d.srcPath,t)}return s}static resolveTargetModules(e,t,r,i){let o=n.getModuleType(t,e.srcPath);return o==="entry"||o==="shared"?[e.name]:Array.from(n.findTopLevelConsumers(e.name,i,t,r))}static dispatchToCollectors(e,t,r,i,o,s){for(let a of e){let c=t.get(a);c&&n.addFileToCollector(c,r,i.fileClass,o,s)}}static flushCollectors(e,t,r,i,o){let s=[];for(let a of r){let c=i.get(a.name);if(!c||!n.hasAnyChange(c))continue;(!o||a.name===o)&&c.hotReloadEntries.length>0&&n.writeApplyFile(e,a.srcPath,t,c.hotReloadEntries),n.writePatchFile(e,a.srcPath,t,c.patchEtsFiles,c.patchRawFiles,c.patchResFiles),s.push(a.name)}return s}static hasAnyChange(e){return e.hotReloadEntries.length>0||e.patchEtsFiles.length>0||e.patchRawFiles.length>0||e.patchResFiles.length>0||e.nativeFiles.length>0}static initEmptyForModule(e,t,r,i){let o=x.join(e,r,"build",t,"intermediates","patch","default"),s=x.join(o,"changedFileList.json");if(z.existsSync(s)||(z.mkdirSync(o,{recursive:!0}),z.writeFileSync(s,JSON.stringify({resources:{resFile:[],rawFile:[]},modifiedFiles:[]}),"utf-8")),!i)return;let a=x.join(e,r,"build",t,"intermediates","hotReload"),c=x.join(a,"changedFileList.json");z.existsSync(c)||(z.mkdirSync(a,{recursive:!0}),z.writeFileSync(c,JSON.stringify({modifiedFilesV2:[]},null,2),"utf-8"))}static loadBuildProfile(e){let t=x.join(e,"build-profile.json5");if(!z.existsSync(t))return null;try{let r=z.readFileSync(t,"utf-8");return hc.parse(r)}catch{return null}}static classifyFile(e,t,r){let i=x.extname(e).toLowerCase();if(i===".ets"||i===".ts")return{fileClass:"ets_ts",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};if(i===".cpp"||i===".cc"||i===".c"||i===".h"||i===".hpp")return{fileClass:"native",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""};let o=e.replace(/\\/g,"/");return o.includes("/resources/rawfile/")?{fileClass:"raw_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:o.includes("/resources/resfile/")?{fileClass:"res_file",moduleSrcPath:n.findModuleByFilePath(e,t,r)?.srcPath??""}:{fileClass:"unknown",moduleSrcPath:""}}static findModuleByFilePath(e,t,r){let i=x.normalize(e);for(let o of r){let s=x.normalize(x.join(t,o.srcPath)),a=s+x.sep;if(i.startsWith(a)||i===s)return o}return null}static getModuleType(e,t){let r=x.join(e,t,"src","main","module.json5");if(!z.existsSync(r))return"entry";try{let i=z.readFileSync(r,"utf-8");return hc.parse(i)?.module?.type||"entry"}catch{return"entry"}}static buildReverseDependencyMap(e,t){let r=new Map;for(let i of t){let o=n.readLocalDependencies(e,i.srcPath);for(let s of o){let a=r.get(s)||[];a.includes(i.name)||a.push(i.name),r.set(s,a)}}return r}static readLocalDependencies(e,t){let r=x.join(e,t,"oh-package.json5");if(!z.existsSync(r))return[];try{let i=z.readFileSync(r,"utf-8"),o=hc.parse(i);return n.resolveDepModuleNames(e,t,o.dependencies||{})}catch{return[]}}static resolveDepModuleNames(e,t,r){let i=n.loadBuildProfile(e);if(!i)return[];let o=i.modules,s=[];for(let a of Object.values(r)){if(typeof a!="string")continue;let c=n.tryResolveDepModule(e,t,a,o);c&&s.push(c)}return s}static tryResolveDepModule(e,t,r,i){let o=r;if(!(o.startsWith("file:")||o.startsWith(".")||o.startsWith("..")))return null;o.startsWith("file:")&&(o=o.substring(5));let a=x.resolve(e,t,o);return i.find(l=>x.resolve(e,l.srcPath)===a)?.name??null}static findTopLevelConsumers(e,t,r,i){let o=new Set,s=new Set,a=[e];for(;a.length>0;){let c=a.shift();s.has(c)||(s.add(c),n.processDependents(c,t,r,i,o,a))}return o}static processDependents(e,t,r,i,o,s){let a=t.get(e)||[];for(let c of a){let l=i.find(g=>g.name===c);if(!l)continue;let d=n.getModuleType(r,l.srcPath);(d==="entry"||d==="shared")&&o.add(c),d==="har"&&s.push(c)}}static addFileToCollector(e,t,r,i,o){let s=x.join(o,i,"src","main","resources");r==="ets_ts"?(e.hotReloadEntries.push({filePath:t,belongProjectPath:o}),e.patchEtsFiles.push(t)):r==="raw_file"?e.patchRawFiles.push({filePath:t,resourcePath:s}):r==="res_file"?e.patchResFiles.push({filePath:t,resourcePath:s}):r==="native"&&e.nativeFiles.push(t)}static writeApplyFile(e,t,r,i){let o=t.replace(/^\.\//,""),s=x.join(e,o,"build",r,"intermediates","hotReload","changedFileList.json"),a=n.readExistingApply(s),c=n.mergeApplyEntries(a,i),l=x.dirname(s);z.existsSync(l)||z.mkdirSync(l,{recursive:!0}),z.writeFileSync(s,JSON.stringify({modifiedFilesV2:c},null,2),"utf-8"),m(`[ChangedFileListWriter] Written hotReload: ${s} (${c.length} entries)`)}static readExistingApply(e){if(!z.existsSync(e))return[];try{let t=z.readFileSync(e,"utf-8");return JSON.parse(t)?.modifiedFilesV2||[]}catch{return[]}}static writePatchFile(e,t,r,i,o,s){let a=t.replace(/^\.\//,""),c=x.join(e,a,"build",r,"intermediates","patch","default","changedFileList.json"),l=n.readExistingPatch(c),d=x.join(e,a,"src","main","ets"),g=i.map(yt=>n.resolveRelativePathForPatch(yt,d)),w=n.mergeStrings(l.modifiedFiles,g),P=n.mergePatchResources(l.rawFile,o),O=n.mergePatchResources(l.resFile,s),te=x.dirname(c);z.existsSync(te)||z.mkdirSync(te,{recursive:!0}),z.writeFileSync(c,JSON.stringify({resources:{resFile:O,rawFile:P},modifiedFiles:w}),"utf-8"),m(`[ChangedFileListWriter] Written patch: ${c}`)}static readExistingPatch(e){if(!z.existsSync(e))return{modifiedFiles:[],rawFile:[],resFile:[]};try{let t=z.readFileSync(e,"utf-8"),r=JSON.parse(t);return{modifiedFiles:r?.modifiedFiles||[],rawFile:r?.resources?.rawFile||[],resFile:r?.resources?.resFile||[]}}catch{return{modifiedFiles:[],rawFile:[],resFile:[]}}}static resolveRelativePathForPatch(e,t){return x.relative(x.normalize(t),x.normalize(e)).replace(/\\/g,"/")}static mergeApplyEntries(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}static mergeStrings(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o)||(r.add(o),i.push(o));return i}static mergePatchResources(e,t){let r=new Set,i=[];for(let o of[...e,...t])r.has(o.filePath)||(r.add(o.filePath),i.push(o));return i}};import Rv from"fs";import{randomUUID as kv}from"crypto";import{execa as Tv}from"execa";var Xn=class{toolProvider;constructor(e){this.toolProvider=e}async install(e,t,r,i=!1){for(let c of t)if(!Rv.existsSync(c)){let l=`Signed hqf file not found: ${c}`;return console.error(`[Apply] ${l}`),{success:!1,message:l}}let s=`/data/local/tmp/${kv()}`,a=[];try{for(let c=0;c<t.length;c++){let l=`${s}/${r}_${c}.hqf`;a.push(l),await this.pushHqf(e,t[c],s,l)}return await this.executeQuickfix(e,a,i)}catch(c){let l=`hqf install error: ${c.message}`;return console.error(`[Apply] ${l}`),{success:!1,message:l}}finally{await this.runHdc(["-t",e,"shell","rm","-rf",s],!1)}}async pushHqf(e,t,r,i){console.log(`[Apply] Pushing hqf to device ${e}: ${t}`),await this.runHdc(["-t",e,"shell","mkdir","-p",r]);let o=await this.runHdc(["-t",e,"file","send",t,i]);if(!o.startsWith("FileTransfer finish"))throw new Error(`Failed to send hqf: ${o}`)}async executeQuickfix(e,t,r=!1){console.log(`[Apply] Installing ${t.length} hqf patch(es) via quickfix...`);let i=["-t",e,"shell","bm","quickfix","-a","-f",...t,"-d"];r||i.push("-o");let o=await this.runHdc(i,!1);if(m(`[InstallHqf] quickfix output: ${o}`),/succe(?:ed|ss)/i.test(o))return console.log("[Apply] hqf installed successfully."),{success:!0,message:"hqf quickfix installed successfully."};let s=`hqf quickfix install failed. Device response: ${o||"(empty)"}. Please try reinstalling the application.`;return console.error(`[Apply] ${s}`),{success:!1,message:s}}async runHdc(e,t=!0){let r=this.toolProvider.hdcPath;m(`[InstallHqf] Executing: ${r} ${e.join(" ")}`);try{let{stdout:i}=await Tv(r,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}};var xv="6.1.1",_o=class{constructor(e,t){this.toolProvider=e;this.projectRoot=t}toolProvider;projectRoot;async execute(e){await Sn(this.projectRoot,()=>this.executeSteps(e),()=>console.log("[Apply] Waiting for another build to finish..."))}async executeSteps(e){this.toolProvider.assertIdeVersion(xv);let t=Zr(e.applyFile,this.projectRoot);console.log(`[Apply] Parsed ${t.length} changed file(s)`);let r=this.writeChangeFileList(e,t),i=await this.buildHqf(e,r);await this.stopApp(e),await this.installHqf(e,i),await this.launchApp(e),console.log("[Apply] Apply complete")}writeChangeFileList(e,t){let r=Kn.writeChangedFileLists(this.projectRoot,e.productName,t);if(r.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");return console.log(`[Apply] changeFileList written for: ${r.writtenModules.join(", ")}`),r.writtenModules}async buildHqf(e,t){return m(`[Apply] hvigor assembleDevHqf --no-daemon (modules=${t.join(",")})`),await Hu(this.toolProvider,this.projectRoot,t,e.productName)}async installHqf(e,t){console.log(`[Apply] Installing ${t.length} hqf(s) to ${e.targetDeviceId}`);let i=await new Xn(this.toolProvider).install(e.targetDeviceId,t,e.bundleName,e.isHotReload??!1);if(!i.success)throw new Error(`hqf install failed: ${i.message}`);console.log("[Apply] hqf installed")}async stopApp(e){let t=new Wt(this.toolProvider);try{await t.forceStopApp(e.targetDeviceId,e.bundleName),console.log("[Apply] app stopped")}catch(r){console.warn(`[Apply] stop app failed: ${r.message}`)}}async launchApp(e){let t=new Wt(this.toolProvider);try{await t.launchApp(e.targetDeviceId,e.bundleName,e.abilityName),console.log("[Apply] app launched")}catch(r){console.warn(`[Apply] launch app failed: ${r.message}`)}}};import Bu from"fs";import*as F from"path";var Fo=class n{static generate(e,t,r,i){let o=dt(e,t),s=F.join(e,o),a=F.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Bu.mkdirSync(a,{recursive:!0}),Bu.writeFileSync(F.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[BuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=F.dirname(i.nodePath)+F.sep,s=F.join(t,"build",r),a=F.join(s,"intermediates"),c=F.join(a,"loader_out",r),l=F.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:F.join(e,"build-profile.json5"),localPropertiesPath:F.join(e,"local.properties"),appResource:F.join(l,"ResourceTable.txt"),cachePath:F.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:F.join(a,"loader",r,"loader.json"),aceModuleJsonPath:F.join(l,"module.json"),aceSoPath:F.join(c,"nativeDependencies.txt"),aceModuleRoot:F.join(t,"src","main","ets"),aceModuleBuild:F.join(c,"ets"),aceProfilePath:F.join(l,"resources","base","profile"),aceSuperVisualPath:F.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:F.join(c,"ets"),changedFileList:F.join(a,"patch","default","changedFileList.json"),patchAbcPath:F.join(a,"patch","default","ets"),removeChangedFileListInSdk:"true"}}}};import Wu from"fs";import*as j from"path";var jo=class n{static generate(e,t,r,i){let o=dt(e,t),s=j.join(e,o),a=j.join(s,"build","config"),c=n.buildConfig(e,s,r,i);Wu.mkdirSync(a,{recursive:!0}),Wu.writeFileSync(j.join(a,"buildConfig.json"),JSON.stringify(c,null,2),"utf-8"),m(`[HotReloadBuildConfigManager] buildConfig.json written to ${a}`)}static buildConfig(e,t,r,i){let o=j.dirname(i.nodePath)+j.sep,s=j.join(t,"build",r),a=j.join(s,"intermediates"),c=j.join(a,"loader_out",r),l=j.join(a,"res",r);return{compileConfig:{deviceType:"default",buildMode:"debug",compilerType:"ark",note:"false",logLevel:"3",hapMode:"false",img2bin:"true",Path:o,projectProfilePath:j.join(e,"build-profile.json5"),localPropertiesPath:j.join(e,"local.properties"),appResource:j.join(l,"ResourceTable.txt"),cachePath:j.join(s,"cache",r,`${r}@CompileArkTS`,"esmodule","debug"),aceBuildJson:j.join(a,"loader",r,"loader.json"),aceModuleJsonPath:j.join(l,"module.json"),aceSoPath:j.join(c,"nativeDependencies.txt"),aceModuleRoot:j.join(t,"src","main","ets"),aceModuleBuild:j.join(c,"ets"),aceProfilePath:j.join(l,"resources","base","profile"),aceSuperVisualPath:j.join(t,"src","main","supervisual"),watchMode:"true"},patchConfig:{enableMap:"true",mode:"hotReload",oldMapFilePath:j.join(c,"ets"),changedFileList:j.join(a,"hotReload","changedFileList.json"),patchAbcPath:j.join(a,"hotReload","patchAbcPath","ets"),removeChangedFileListInSdk:"true"}}}};import Gu from"crypto";import je from"fs";import He from"path";import Vu from"os";import{io as Nv}from"socket.io-client";var Lv=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Zn=class n{projectRoot;toolProvider;cachedSocket=null;cachedDaemonPort=0;constructor(e,t){this.projectRoot=e,this.toolProvider=t}async sendHotCompile(e){await this.waitForDaemonReady();let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Run `devecocli run --hotreload` first.");return this.sendViaSocket(t,e)}async startWatchSession(e){await this.waitForDaemonReady(),console.log(`[DaemonClient] Compiling, build with: ${JSON.stringify(e)}`);let t=this.findProjectDaemon();if(!t?.sessionId)throw new Error("No running hvigor daemon with sessionId found. Build the hap first.");let r=await this.getOrCreateSocket(t),i=this.watchLogPath;je.mkdirSync(He.dirname(i),{recursive:!0}),je.writeFileSync(i,"");let o=this.createWatchLogBuffer(i);r.on("WatchLog",o.onWatchLog),r.on("WatchResult",o.onWatchResult),await this.awaitInitialBuild(r,e)}createWatchLogBuffer(e){let r=[];return{onWatchLog:s=>{let a=n.extractText(s);a.trim()&&(r.push(a.endsWith(`
|
|
33
33
|
`)?a:a+`
|
|
34
34
|
`),r.length>100&&r.shift())},onWatchResult:s=>{let a=n.extractText(s);if(!a.trim())return;let c=`[WatchResult] ${a}`;console.log(c),je.writeFileSync(e,[...r,c+`
|
|
35
|
-
`].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return He.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let r=
|
|
35
|
+
`].join("")),r.length=0}}}awaitInitialBuild(e,t){return new Promise((r,i)=>{let o=!1,s=this.createOutputHandler(),a=l=>{!l?.status||o||(l.status==="finish"?(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),r()):(l.status==="reject"||l.status==="close")&&(o=!0,e.off("disconnect",c),e.off("Output",s),e.off("BuildStatus",a),this.invalidateSocket(),i(new Error(l.reason||`Watch-session build ${l.status}`))))},c=l=>{o||(o=!0,i(new Error(`Socket disconnected: ${l}`)))};e.on("disconnect",c),e.on("Output",s),e.on("BuildStatus",a),e.emit("CommonBuild",this.buildStartOptions(t)),console.log("[DaemonClient] Compiling, waiting for build to finish...")})}getWatchLogPath(){return this.watchLogPath}get watchLogPath(){return He.join(this.projectRoot,".hvigor","hotreload-watch.log")}buildStartOptions(e){let t={_:["assembleHap"],daemon:!0,watch:!0,hotReloadBuild:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildStartOptions:",JSON.stringify(t,null,2)),t}disconnect(){this.invalidateSocket()}async getOrCreateSocket(e){if(this.cachedSocket&&this.cachedDaemonPort===e.port){if(this.cachedSocket.connected)return this.cachedSocket;this.invalidateSocket()}let t=this.decryptSessionId(e.sessionId);console.log(`[DaemonClient] Socket.IO connect: ws://127.0.0.1:${e.port} (${e.state})`);let r=Nv(`ws://127.0.0.1:${e.port}`,{transports:["websocket"],path:`/${t}`});return await new Promise((i,o)=>{let s=setTimeout(()=>{o(new Error("Socket connect timeout (10s)"))},1e4);r.once("connect",()=>{clearTimeout(s),i()}),r.once("connect_error",a=>{clearTimeout(s),o(new Error(`Socket connect error: ${a.message}`))})}),this.cachedSocket=r,this.cachedDaemonPort=e.port,r}invalidateSocket(){this.cachedSocket&&(this.cachedSocket.removeAllListeners(),this.cachedSocket.disconnect(),this.cachedSocket=null,this.cachedDaemonPort=0)}async sendViaSocket(e,t){let r=await this.getOrCreateSocket(e);return new Promise((i,o)=>{let s=!1,a=Date.now(),c=this.createHotCompileHandlers(r,()=>s,d=>s=d,o),l=d=>{!d?.status||s||(d.status==="finish"?(s=!0,c.detach(),r.off("BuildStatus",l),console.log(`[Timing] abc compile: ${Date.now()-a}ms`),i(d.exitCode??0)):(d.status==="reject"||d.status==="close")&&(s=!0,c.detach(),r.off("BuildStatus",l),this.invalidateSocket(),o(new Error(`Hot compile ${d.status}: ${d.reason||"see WatchLog/Output above for compile errors"}`))))};r.on("disconnect",c.onDisconnect),r.on("Output",c.onOutput),r.on("BuildStatus",l),r.on("WatchLog",c.onWatchLog),r.on("WatchResult",c.onWatchResult),r.on("WatchCompileResult",c.onWatchCompileResult),r.on("WatchCompileData",c.onWatchCompileData),r.emit("CommonBuild",this.buildCompileOptions(t)),console.log("[DaemonClient] Compiling, waiting for hot compile to finish...")})}static extractText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="object"){let t=e;if(typeof t.text=="string")return t.text;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message}return JSON.stringify(e)}createHotCompileHandlers(e,t,r,i){let o=w=>{t()||(r(!0),g(),this.invalidateSocket(),i(new Error(`Socket disconnected: ${w}`)))},s=this.createOutputHandler(),{onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d}=this.getDataHandler(),g=()=>{e.off("disconnect",o),e.off("Output",s),e.off("WatchLog",a),e.off("WatchResult",c),e.off("WatchCompileResult",l),e.off("WatchCompileData",d)};return{onDisconnect:o,onOutput:s,onWatchLog:a,onWatchResult:c,onWatchCompileResult:l,onWatchCompileData:d,detach:g}}getDataHandler(){let e=n.extractText;return{onWatchLog:s=>{let a=e(s);a.trim()&&process.stdout.write(a+(a.endsWith(`
|
|
36
36
|
`)?"":`
|
|
37
|
-
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!je.existsSync(e))return null;try{let t=je.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=He.join(t,"fd"),i=He.join(t,"ac"),o=He.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(Rv)]),c=this.readSingleFile(i),l=Wu.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Wu.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=je.readdirSync(e).map(r=>He.join(e,r)).filter(r=>je.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=je.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return je.readFileSync(He.join(r,i[0]))})}readSingleFile(e){let t=je.readdirSync(e).map(r=>He.join(e,r)).filter(r=>je.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return je.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||He.join(Gu.homedir(),".hvigor");return He.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||He.join(Gu.homedir(),".hvigor");return He.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import qu from"fs";import*as bt from"path";import{green as Bo,yellow as hc}from"colorette";import Dn from"fs";import*as Rn from"path";import kv from"json5";var Tv=2e6,xv=1e6,Lv="hotreload",Ho=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Rn.resolve(e,t),s=Rn.join(o,"patch.json"),a;return Dn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:Tv,versionCode:i.versionCode},module:{name:r,type:Lv}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Rn.join(e,"AppScope","app.json5");if(!Dn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Dn.readFileSync(t,"utf-8"),i=kv.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??xv;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Dn.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Rn.dirname(e);Dn.existsSync(r)||Dn.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Dn.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import ce from"fs";import*as H from"path";import Vu from"crypto";import Nv from"json5";import{execa as zu}from"execa";var $o=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=H.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=H.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(H.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(H.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=Vu.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=Vu.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ce.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=H.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(ce.statSync(e).isDirectory()){let i=ce.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(ce.readFileSync(H.join(e,i[0])))}return new Int8Array(ce.readFileSync(e))}},Uo=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${H.dirname(e.javaPath)}${H.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i){let o=this.checkAbcExists(t);if(!o.exists)return{signedHqfPaths:[],message:o.message};let s=this.resolveHqfPaths(e,i);return await this.generateHqf(r,o.abcPath,s.unsignedHqfPath)?this.signHqfDirect(s.unsignedHqfPath,s.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:s.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=H.join(e,"ets","modules.abc");if(ce.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!ce.existsSync(e))return null;let t=ce.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=H.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=dt(this.projectRoot,e),i=H.join(this.projectRoot,r,"build",t,"outputs","default");return ce.existsSync(i)||ce.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:H.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:H.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=H.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await zu(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):ce.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath;m(`[GenSignHqf] Signing: ${o} ${i.join(" ")}`);try{let s=Date.now(),a=await zu(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.exitCode}`):ce.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(s){return this.signFailResult(e,`hqf signing failed: ${s.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=$o.decryptPwd(r,t.storePassword,"storePassword"),o=$o.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=H.resolve(e.storeFile,".."),r=H.join(t,"material");return ce.existsSync(r)?t:null}readSigningConfig(e){let t=H.join(this.projectRoot,"build-profile.json5");if(!ce.existsSync(t))return null;try{let r=ce.readFileSync(t,"utf-8"),i=Nv.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[H.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),H.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(ce.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[H.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),H.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(ce.existsSync(r))return r;return null}};async function Yu(n){let e=Date.now(),t=dt(n.projectPath,n.moduleName),r=Ov(n);console.log(hc("[HotReload] Ensure the project source is trusted before proceeding."));let i=Mv(n),o=Zr(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),_v(n,o),Fv(n,t),await jv(n,i);let s=bt.join(n.projectPath,t,"patch.json"),a=await $v(n,t,s);return await Uv(n,a),console.log(Bo("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function Ov(n){if(bt.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return bt.join(n.projectPath,".hvigor",n.applyFileName)}function Mv(n){let{projectPath:e,toolProvider:t}=n,r=new Zn(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function _v(n,e){let t=Kn.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Bo(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(hc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Fv(n,e){let t=Ho.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Bo(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function jv(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=Hv(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
|
|
37
|
+
`))},onWatchResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchResult] ${a}`)},onWatchCompileResult:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileResult] ${a}`)},onWatchCompileData:s=>{let a=e(s);a.trim()&&console.log(`[WatchCompileData] ${a}`)}}}createOutputHandler(){return e=>{let t=typeof e.text=="string"?e.text:Buffer.from(e.text).toString(e.encoding??"utf-8");t.trim()&&(e.type==="stderr"?process.stderr.write(t):process.stdout.write(t))}}buildCompileOptions(e){let t={_:["assembleDevHqf"],daemon:!0,hotCompile:!0,mode:"module",prop:[`module=${e.moduleSpecs.join(",")}`,`product=${e.productName}`,"debuggable=true","hotReload=true","requiredDeviceType=phone"],parallel:!0,incremental:!0,analyze:"normal",env:{DEVECO_SDK_HOME:this.toolProvider.sdkPath}};return console.log("[DaemonClient] buildCompileOptions:",JSON.stringify(t,null,2)),t}async waitForDaemonReady(){let r=Date.now();for(;Date.now()-r<3e4;){let i=this.findProjectDaemon();if(i&&(i.state==="half_busy"||i.state==="idle"))return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first.")}findProjectDaemon(){let e=this.getRegistryPath();if(!je.existsSync(e))return null;try{let t=je.readFileSync(e,"utf-8"),r=JSON.parse(t),i=Object.values(r).filter(o=>o.cwdPath===this.projectRoot&&(o.state==="idle"||o.state==="half_busy"||o.state==="busy")&&this.isProcessAlive(o.pid));return i.length>0?i[i.length-1]:null}catch{return null}}decryptSessionId(e){let t=this.getMetaDir(),r=He.join(t,"fd"),i=He.join(t,"ac"),o=He.join(t,"ce"),s=this.readComponents(r),a=this.xorBuffers([s[0],s[1],s[2],Buffer.from(Lv)]),c=this.readSingleFile(i),l=Gu.pbkdf2Sync(Buffer.from(a).toString(),c,1e4,16,"sha256"),d=this.readSingleFile(o),g=this.aesGcmDecrypt(l,d),w=Buffer.from(e,"hex");return this.aesGcmDecrypt(g,w).toString("utf-8")}aesGcmDecrypt(e,t){let r=0,i=t.readUInt32BE(r);r+=4;let o=t.subarray(r,r+12);r+=12;let s=i-16,a=t.subarray(r,r+s);r+=s;let c=t.subarray(r,r+16),l=Gu.createDecipheriv("aes-128-gcm",e,o);return l.setAuthTag(c),Buffer.concat([l.update(a),l.final()])}readComponents(e){let t=je.readdirSync(e).map(r=>He.join(e,r)).filter(r=>je.statSync(r).isDirectory()).sort();if(t.length<3)throw new Error(`Expected 3 subdirectories in ${e}, found ${t.length}`);return t.slice(0,3).map(r=>{let i=je.readdirSync(r);if(i.length===0)throw new Error(`No file in ${r}`);return je.readFileSync(He.join(r,i[0]))})}readSingleFile(e){let t=je.readdirSync(e).map(r=>He.join(e,r)).filter(r=>je.statSync(r).isFile());if(t.length===0)throw new Error(`No file in ${e}`);return je.readFileSync(t[0])}xorBuffers(e){let t=Buffer.alloc(e[0].length);t.set(e[0]);for(let r=1;r<e.length;r++){let i=Buffer.isBuffer(e[r])?e[r]:Buffer.from(e[r]);for(let o=0;o<t.length;o++)t[o]^=i[o]}return t}getRegistryPath(){let e=process.env.HVIGOR_USER_HOME||He.join(Vu.homedir(),".hvigor");return He.join(e,"daemon","cache","daemon-sec.json")}getMetaDir(){let e=process.env.HVIGOR_USER_HOME||He.join(Vu.homedir(),".hvigor");return He.join(e,"meta")}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}};import Yu from"fs";import*as Et from"path";import{green as Bo,yellow as gc}from"colorette";import Dn from"fs";import*as Rn from"path";import Ov from"json5";var Mv=2e6,_v=1e6,Fv="hotreload",Ho=class n{static generateOrUpdate(e,t,r){let i=n.readAppConfig(e),o=Rn.resolve(e,t),s=Rn.join(o,"patch.json"),a;return Dn.existsSync(s)?(m(`[PatchManager] patch.json found at ${s}, incrementing patchVersionCode`),a=n.readExistingPatch(s),a.app.patchVersionCode+=1):(m(`[PatchManager] patch.json not found, generating new one at ${s}`),a={app:{bundleName:i.bundleName,patchVersionCode:Mv,versionCode:i.versionCode},module:{name:r,type:Fv}}),n.writePatchJson(s,a),a}static readAppConfig(e){let t=Rn.join(e,"AppScope","app.json5");if(!Dn.existsSync(t))throw new Error(`AppScope/app.json5 not found at ${t}. Unable to read bundleName and versionCode.`);let r=Dn.readFileSync(t,"utf-8"),i=Ov.parse(r),o=i?.app?.bundleName;if(!o)throw new Error("bundleName is missing in AppScope/app.json5");let s=i?.app?.versionCode??_v;return{bundleName:o,versionCode:s}}static readExistingPatch(e){let t=Dn.readFileSync(e,"utf-8"),r=JSON.parse(t);if(!r?.app?.patchVersionCode)throw new Error(`Invalid patch.json at ${e}: missing app.patchVersionCode`);return r}static writePatchJson(e,t){let r=Rn.dirname(e);Dn.existsSync(r)||Dn.mkdirSync(r,{recursive:!0});let i=JSON.stringify(t,null,2);Dn.writeFileSync(e,i,"utf-8"),m(`[PatchManager] patch.json written to ${e}`),m(`[PatchManager] Content: ${i}`)}};import ce from"fs";import*as H from"path";import zu from"crypto";import jv from"json5";import{execa as qu}from"execa";var $o=class n{static COMPONENT=new Int8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]);static DIRS=["fd","ac","ce"];static decryptPwd(e,t,r){if(t.length<32||t.length%2!==0)throw new Error(`Invalid encrypted password for ${r}`);m(`[DecipherUtil] Decrypting ${r}, encrypted length: ${t.length}`);let i=H.resolve(e,"material"),o=n.getKey(i,r),s=new Int8Array(Buffer.from(t,"hex"));return m(`[DecipherUtil] Data length: ${s.length}, key length: ${o.length}`),n.decrypt(o,s).toString("utf-8")}static getKey(e,t){let r=H.resolve(e,n.DIRS[0]),i=n.readFd(r,t),o=n.readDirBytes(H.resolve(e,n.DIRS[1]),t),s=n.getRootKey(i,o,t),a=n.readDirBytes(H.resolve(e,n.DIRS[2]),t);return new Int8Array(n.decrypt(s,a))}static getRootKey(e,t,r){if(!e.every(a=>a.length===16))throw new Error(`Signing material data error for ${r}`);let i=[...e,n.COMPONENT],o=n.xor(i[0],i[1],r);for(let a=2;a<i.length;a++)o=n.xor(o,i[a],r);let s=zu.pbkdf2Sync(Buffer.from(o).toString(),Buffer.from(t),1e4,16,"sha256");return new Int8Array(s)}static xor(e,t,r){if(e.byteLength!==t.byteLength)throw new Error(`Signing material data error for ${r}`);let i=new Int8Array(e.byteLength);for(let o=0;o<e.byteLength;o++)i[o]=e[o]^t[o];return i}static decrypt(e,t){let r=(255&t[0])<<24|(255&t[1])<<16|(255&t[2])<<8|255&t[3],i=t.length-4-r,o=t.slice(4,4+i),s=t.slice(t.length-16),a=zu.createDecipheriv("aes-128-gcm",Buffer.from(e),Buffer.from(o));a.setAuthTag(Buffer.from(s));let c=a.update(Buffer.from(t.subarray(4+i,t.length-16))),l=a.final();return Buffer.concat([c,l])}static readFd(e,t){let r=ce.readdirSync(e).filter(o=>o!==".DS_Store");if(r.length!==3)throw new Error(`fd directory must have 3 entries for ${t}`);let i=[];for(let o of r){let s=H.join(e,o);i.push(n.readDirBytes(s,t))}return i}static readDirBytes(e,t){if(ce.statSync(e).isDirectory()){let i=ce.readdirSync(e).filter(o=>o!==".DS_Store");if(i.length!==1)throw new Error(`Expected exactly 1 file in ${e} for ${t}`);return new Int8Array(ce.readFileSync(H.join(e,i[0])))}return new Int8Array(ce.readFileSync(e))}},Uo=class{toolProvider;projectRoot;env;constructor(e,t){this.toolProvider=e,this.projectRoot=t;let i=`${H.dirname(e.javaPath)}${H.delimiter}${process.env.PATH||""}`;this.env={...process.env,PATH:i,DEVECO_SDK_HOME:e.sdkPath}}async generateAndSign(e,t,r,i,o=!1){let s=this.checkAbcExists(t);if(!s.exists)return{signedHqfPaths:[],message:s.message};let a=this.resolveHqfPaths(e,i);return await this.generateHqf(r,s.abcPath,a.unsignedHqfPath)?o?{success:!0,signedHqfPaths:[a.unsignedHqfPath],unsignedHqfPath:a.unsignedHqfPath,message:"Unsigned hqf generated (signing skipped for emulator)."}:this.signHqfDirect(a.unsignedHqfPath,a.signedHqfPath):{signedHqfPaths:[],unsignedHqfPath:a.unsignedHqfPath,message:"Failed to generate unsigned hqf."}}checkAbcExists(e){let t=H.join(e,"ets","modules.abc");if(ce.existsSync(t))return{exists:!0,abcPath:t,message:"abc file exists."};let r=this.findFirstAbc(e);return r?{exists:!0,abcPath:r,message:"abc file exists."}:{exists:!1,abcPath:"",message:`abc file not found in ${e}.`}}findFirstAbc(e){if(!ce.existsSync(e))return null;let t=ce.readdirSync(e,{withFileTypes:!0});for(let r of t){let i=H.join(e,r.name);if(r.isDirectory()){let o=this.findFirstAbc(i);if(o)return o}else if(r.isFile()&&r.name.endsWith(".abc"))return i}return null}resolveHqfPaths(e,t){let r=dt(this.projectRoot,e),i=H.join(this.projectRoot,r,"build",t,"outputs","default");return ce.existsSync(i)||ce.mkdirSync(i,{recursive:!0}),{unsignedHqfPath:H.join(i,`${e}-default-unsigned.hqf`),signedHqfPath:H.join(i,`${e}-default-signed.hqf`)}}async generateHqf(e,t,r){let i=this.resolvePackingTool();if(!i)return console.error("[HotReload] app_packing_tool.jar not found in SDK."),!1;let o=H.dirname(t),s=this.toolProvider.javaPath,a=["-jar",i,"--mode","hqf","--json-path",e,"--ets-path",o,"--out-path",r,"--force","true"];m(`[GenSignHqf] Packing: ${s} ${a.join(" ")}`);try{let c=Date.now(),l=await qu(s,a,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] pack (JVM#1): ${Date.now()-c}ms`),l.stdout&&console.log(l.stdout),l.stderr&&console.error(l.stderr),l.exitCode!==0?(console.error(`[HotReload] app_packing_tool failed with exit code ${l.exitCode}`),!1):ce.existsSync(r)?(console.log(`[HotReload] Unsigned hqf generated: ${r}`),!0):(console.error(`[HotReload] hqf not generated at ${r}`),!1)}catch(c){return console.error(`[HotReload] Packing hqf failed: ${c.message}`),!1}}async signHqfDirect(e,t){let r=this.resolveSignConfig();if(!r)return this.signFailResult(e,"Signing prerequisites not met.");let i=this.buildSignArgs(r,e,t),o=this.toolProvider.javaPath;m(`[GenSignHqf] Signing: ${o} ${i.join(" ")}`);try{let s=Date.now(),a=await qu(o,i,{cwd:this.projectRoot,stdout:"pipe",stderr:"pipe",reject:!1});return console.log(`[Timing] sign (JVM#2): ${Date.now()-s}ms`),a.stdout&&console.log(a.stdout),a.stderr&&console.error(a.stderr),a.exitCode!==0?this.signFailResult(e,`hqf signing failed with exit code ${a.exitCode}`):ce.existsSync(t)?(console.log(`[HotReload] Signed hqf generated: ${t}`),{success:!0,signedHqfPaths:[t],unsignedHqfPath:e,message:"hqf generated and signed successfully."}):this.signFailResult(e,`Signed hqf not generated at ${t}`)}catch(s){return this.signFailResult(e,`hqf signing failed: ${s.message}`)}}resolveSignConfig(){let e=this.resolveSignTool();if(!e)return null;let t=this.readSigningConfig("default");if(!t?.storeFile||!t?.certpath||!t?.profile)return null;let r=this.resolveMaterialDir();if(!r)return null;try{let i=$o.decryptPwd(r,t.storePassword,"storePassword"),o=$o.decryptPwd(r,t.keyPassword,"keyPassword");return{signToolPath:e,storePwd:i,keyPwd:o,signingConfig:t}}catch{return null}}buildSignArgs(e,t,r){return["-jar",e.signToolPath,"sign-app","-mode","localSign","-keyAlias",e.signingConfig.keyAlias||"debugKey","-keyPwd",e.keyPwd,"-keystoreFile",e.signingConfig.storeFile,"-keystorePwd",e.storePwd,"-appCertFile",e.signingConfig.certpath,"-profileFile",e.signingConfig.profile,"-inFile",t,"-outFile",r,"-signAlg",e.signingConfig.signAlg||"SHA256withECDSA"]}resolveMaterialDir(){let e=this.readSigningConfig("default");if(!e?.storeFile)return null;let t=H.resolve(e.storeFile,".."),r=H.join(t,"material");return ce.existsSync(r)?t:null}readSigningConfig(e){let t=H.join(this.projectRoot,"build-profile.json5");if(!ce.existsSync(t))return null;try{let r=ce.readFileSync(t,"utf-8"),i=jv.parse(r),s=i.app?.products?.find(a=>a.name===e)?.signingConfig;return s?i.app?.signingConfigs?.find(a=>a.name===s)?.material??null:null}catch{return null}}resolveSignTool(){let e=this.toolProvider.sdkPath,t=[H.join(e,"default","openharmony","toolchains","lib","hap-sign-tool.jar"),H.join(e,"toolchains","lib","hap-sign-tool.jar")];for(let r of t)if(ce.existsSync(r))return r;return null}signFailResult(e,t){return console.error(`[HotReload] ${t}`),{success:!1,signedHqfPaths:[],unsignedHqfPath:e,message:t}}resolvePackingTool(){let e=this.toolProvider.sdkPath,t=[H.join(e,"default","openharmony","toolchains","lib","app_packing_tool.jar"),H.join(e,"toolchains","lib","app_packing_tool.jar")];for(let r of t)if(ce.existsSync(r))return r;return null}};async function Ju(n){let e=Date.now(),t=dt(n.projectPath,n.moduleName),r=Hv(n);console.log(gc("[HotReload] Ensure the project source is trusted before proceeding."));let i=$v(n),o=Zr(r,n.projectPath);console.log(`[HotReload] Parsed ${o.length} changed file(s) from ${n.applyFileName}`),Uv(n,o),Bv(n,t),await Wv(n,i);let s=Et.join(n.projectPath,t,"patch.json"),a=await Vv(n,t,s);return await zv(n,a),console.log(Bo("[HotReload] hot reload applied successfully (app not restarted).")),console.log(`[Timing] TOTAL executeHotReloadApply: ${Date.now()-e}ms`),{success:!0,message:"Hot reload applied successfully."}}function Hv(n){if(Et.basename(n.applyFileName)!==n.applyFileName)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${n.applyFileName}`);return Et.join(n.projectPath,".hvigor",n.applyFileName)}function $v(n){let{projectPath:e,toolProvider:t}=n,r=new Zn(e,t);if(!r.findProjectDaemon())throw new Error("No running hvigor daemon found. Run `devecocli run --hotreload` first to start the daemon.");return r}function Uv(n,e){let t=Kn.writeChangedFileLists(n.projectPath,n.productName,e,n.moduleName);if(t.writtenModules.length===0)throw new Error("No changed files belong to a runnable module");console.log(Bo(`[HotReload] changedFileList written for: ${t.writtenModules.join(", ")}`)),t.skippedFiles.length>0&&console.warn(gc(`[HotReload] skipped ${t.skippedFiles.length} file(s)`))}function Bv(n,e){let t=Ho.generateOrUpdate(n.projectPath,e,n.moduleName);console.log(Bo(`[HotReload] patch.json ready (patchVersionCode=${t.app.patchVersionCode})`))}async function Wv(n,e){let t=Date.now(),r=e.getWatchLogPath();try{console.log("[HotReload] Daemon hot compile (socket short connection)...");let i=await e.sendHotCompile({moduleSpecs:n.moduleSpecs,productName:n.productName});if(i!==0){let o=Gv(r);throw new Error(`Daemon hot compile exited with code ${i}`+(o?`
|
|
38
38
|
--- compile output (from watch session) ---
|
|
39
|
-
${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function
|
|
40
|
-
`):""}catch{return""}}async function
|
|
41
|
-
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function
|
|
39
|
+
${o}`:""))}}finally{e.disconnect()}console.log(`[Timing] daemon hot compile: ${Date.now()-t}ms`)}function Gv(n){try{return Yu.existsSync(n)?Yu.readFileSync(n,"utf8").split(/\r?\n/).filter(t=>t.trim()).slice(-40).join(`
|
|
40
|
+
`):""}catch{return""}}async function Vv(n,e,t){let r=Et.join(n.projectPath,e,"build",n.productName,"intermediates"),i=[Et.join(r,"hotReload","patchAbcPath"),Et.join(r,"patch","default")],o=Date.now(),s=new Uo(n.toolProvider,n.projectPath),a=n.targetDeviceId.includes("127.0.0.1")||n.targetDeviceId.includes("localhost"),c=null;for(let l of i){let d=await s.generateAndSign(n.moduleName,l,t,n.productName,a);if(d.success&&d.signedHqfPaths.length>0){c=d;break}c=d}if(console.log(`[Timing] gen+sign hqf: ${Date.now()-o}ms`),!c?.success||c.signedHqfPaths.length===0)throw new Error(`hqf generation/signing failed (no abc found in any candidate). Last: ${c?.message??"unknown"}`);return c.signedHqfPaths}async function zv(n,e){let t=Date.now(),i=await new Xn(n.toolProvider).install(n.targetDeviceId,e,n.bundleName,!0);if(console.log(`[Timing] quickfix install: ${Date.now()-t}ms`),!i.success)throw new Error(`hqf install failed: ${i.message}`)}function yc(n,e){if(!n||n.length===0)throw new Error(`Hot reload requires --module <name> (a single target module; har deps are fine). Got: '${e??""}' (no --module passed).`)}function Ku(n,e,t){let r=Et.join(n.rootDir,".hvigor",t),i;try{i=Zr(r,n.rootDir)}catch{return}let o=new Set;for(let s of i){let a=n.findOwningModule(s);if(!a||a===e)continue;let c=n.getModuleType(a);(c==="feature"||c==="shared")&&o.add(`${a} (${c})`)}o.size>0&&console.warn(gc(`[HotReload] Changed files belong to feature/hsp dependency module(s): ${[...o].join(", ")}. These are NOT hot-reloadable \u2014 run \`devecocli run\` (full redeploy) for them. Only the target module (+ har deps) will be hot-reloaded this time.`))}function Xu(n,e,t,r,i){let o=new Set,s=n.collectNonHarDependentModuleList(e);for(let a of s)o.add(n.findArtifactPath(a,t,r,i));return o.add(n.findArtifactPath(e,t,r,i)),[...o]}async function Zu(n,e){await new Me(n,e.rootDir).stopDaemon(),console.log(Bo("Hvigor daemon stopped."))}function wc(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 Vo(n,e){let t=await n.listDevices();if(t.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await n.listDevicesWithName();throw new Error("Multiple devices found. Specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
41
|
+
`))}let r=await n.getDeviceInfo(t,e);if(!r)throw new Error("No active devices found.");if(!e){let i=await n.getDeviceName(r.serial);console.log(`Auto-selected device: ${i} (${r.serial})`)}return r.serial}function vc(n,e){if(e&&e.length>0)return e;let t=n.profile.modules.filter(r=>{let i=n.getModuleType(r.name);return i==="entry"||i==="feature"||i==="shared"});if(t.length===1){let r=t[0].name;return console.log(`Auto-selected module: ${r}`),[r]}throw new Error(`Specify module(s) using --module <name> [<name>...].
|
|
42
42
|
Available runnable modules:
|
|
43
43
|
`+t.map(r=>` - ${r.name}`).join(`
|
|
44
|
-
`))}function
|
|
44
|
+
`))}function Qu(n,e,t){if(t)return t;let r=e.find(({moduleName:o})=>n.getModuleType(o)==="entry");if(r)return n.getMainAbility(r.moduleName);let i=e.find(({moduleName:o})=>n.getModuleType(o)==="feature");if(i)return n.getMainAbility(i.moduleName)}async function ep(n,e,t,r,i,o){if(o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
|
|
45
45
|
Installing artifacts to device ${e}...`),await n.installApp(e,r),i){console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(ei(`
|
|
46
46
|
Application '${t}': ${s}`))}else console.log(`
|
|
47
|
-
Application '${t}' installed successfully (no ability to launch).`)}var
|
|
48
|
-
`+ei("Build completed successfully."))}async function
|
|
49
|
-
${t} is already up to date (v${n}, tag: ${e})`));return}console.log(
|
|
50
|
-
New version found: ${i} (current: ${n})`)),console.log(
|
|
51
|
-
`+
|
|
52
|
-
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:
|
|
53
|
-
`).trim(),a=
|
|
54
|
-
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Yo(t),i=
|
|
47
|
+
Application '${t}' installed successfully (no ability to launch).`)}var Jv=new qv("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--apply <fileName>","Quick-apply changed files via quickfix (incremental hqf) and restart. <fileName> under project .hvigor/").option("--hotreload [action]",'Start hot-reload mode (build+deploy with daemon, then exit). Use "stop" to shut down the hvigor daemon.').option("--hotreload-apply <fileName>","Hot-reload changed files (.hvigor/<fileName> list) via daemon hot compile + signed hqf + quickfix, without restarting the app.").action(async n=>{try{await Xv(n)}catch(e){console.error(Yv(e.message)),process.exit(1)}});async function Kv(n,e,t,r,i){let o=new Vn(e,n.rootDir),s=new Me(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:P}of t)for(let O of n.collectNonHarDependentModuleList(w))a.add(`${O}@${P}`),c.add(O);let l=[...a],d=cc(n,l),g={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)Fo.generate(n.rootDir,w,r,e);await Sn(n.rootDir,()=>lc(o,s,r,i,g,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
48
|
+
`+ei("Build completed successfully."))}async function Xv(n){let e=V.discover(process.cwd());console.warn(Wo("Ensure the project source is trusted before proceeding."));let t=await A.new();if(n.skipBuild||t.assertJava(),n.hotreloadApply){await Qv(n,e,t);return}if(n.hotreload){await Zv(n,e,t);return}if(n.apply){await tS(n,e,t);return}await tp(n,e,t)}async function Zv(n,e,t){if(n.hotreload==="stop"){await Zu(t,e);return}let i=vc(e,n.module).map(wc),{moduleName:o,targetName:s}=i[0];yc(n.module,o);let a=new Wt(t),c=Z.from(t),l=await Vo(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),g=n.product||"default";e.validateProduct(g);let w=e.getBundleName(),P=Qu(e,i,n.ability);jo.generate(e.rootDir,o,g,t);let O=new Me(t,e.rootDir);console.log(ei("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await O.ensureDaemonRunning();let te=[`${o}@${g}`];for(let Mt of e.collectNonHarDependentModuleList(o))te.includes(`${Mt}@${g}`)||te.push(`${Mt}@${g}`);console.log(ei("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)...")),await new Zn(e.rootDir,t).startWatchSession({moduleSpecs:te,productName:g});let at=Xu(e,o,s,d,g);await ep(a,l,w,at,P,!!n.uninstall),console.log(ei("Hot-reload watch session active (socket persistent). Edit code, write .hvigor/<file>, then `devecocli run --hotreload-apply <file>` in another terminal. Ctrl+C here to stop.")),await new Promise(()=>{})}async function Qv(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let i=vc(e,n.module),{moduleName:o}=wc(i[0]);yc(n.module,o);let s=Z.from(t),a=await Vo(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Ku(e,o,r);let d=[`${o}@${c}`],g=await Ju({applyFileName:r,projectPath:e.rootDir,moduleName:o,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!g.success)throw new Error(g.message)}function eS(n,e,t,r){let i=new Set;for(let{moduleName:o,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(o)){i.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))i.add(c)}return[...i]}async function tp(n,e,t){let i=vc(e,n.module).map(wc);for(let{moduleName:O}of i){let te=e.getModuleType(O);if(te!=="entry"&&te!=="feature"&&te!=="shared")throw new Error(`Module '${O}' '${te}' is not runnable. Specify an entry or feature module.`)}let o=new Wt(t),s=Z.from(t),a=await Vo(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let d=n.buildMode||"debug";n.skipBuild||await Kv(e,t,i,l,d);let g=eS(e,i,c,l),w=e.getBundleName(),P=Qu(e,i,n.ability);await ep(o,a,w,g,P,!!n.uninstall)}async function tS(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(Go.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let i=Go.join(e.rootDir,".hvigor",r),o=Z.from(t),s=await Vo(o,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",g=new _o(t,e.rootDir);try{await g.execute({applyFile:i,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(Wo("[Apply] \u5B8C\u6210\u3002\u82E5\u6539\u52A8\u672A\u751F\u6548\uFF0C\u8BF7\u68C0\u67E5 <module>/build/config/buildConfig.json \u662F\u5426\u6709\u5185\u5BB9\uFF0C\u6216\u6267\u884C devecocli run \u5168\u91CF\u6784\u5EFA\u3002"));return}catch(w){console.warn(Wo(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(Wo("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await tp(n,e,t)}var np=Jv;import{Command as lS}from"commander";import*as lp from"path";import{green as ap,red as cp,cyan as bc}from"colorette";import{execa as Pc}from"execa";import{spawn as oS}from"child_process";import*as sp from"fs";import*as qo from"path";import{yellow as sS}from"colorette";import aS from"proper-lockfile";import*as Gt from"fs";import*as rp from"path";import{homedir as nS}from"os";var rS="deveco-cli",Sc,kn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function ip(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Wa(n))||rp.join(nS(),".local","share",rS);try{return po(t)}catch(r){throw new kn(r instanceof Error?r.message:String(r))}}async function op(){let n=ip();await Gt.promises.mkdir(n,{recursive:!0});let e;try{e=await Gt.promises.realpath(n)}catch(r){throw new kn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await Gt.promises.stat(e)).isDirectory())throw new kn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Sc=e,e}function ut(){if(Sc!==void 0)return Sc;let n=ip();try{if(Gt.existsSync(n))return Gt.realpathSync(n)}catch{}return n}function zo(){return"@deveco-test/deveco-cli"}function Vt(){return"1.3.0-Test.13"}function Qn(){return"daily"}function er(){let n=process.env.DEVECO_CLI_DISABLE_UPDATE;return n==="check"||n==="all"?n:"off"}import*as ti from"fs";import*as ni from"path";var iS={lastCheckedTimestamp:null,latestVersion:null,blockedVersions:[],checkError:null},Ec=new Map,zt=class n{static CHECK_WINDOW_HOUR=21;static ONE_DAY_MS=1440*60*1e3;cacheFilePath;lockFilePath;constructor(e){this.cacheFilePath=ni.join(e,"cache.json"),this.lockFilePath=ni.join(e,"check.lock")}async writeSuccess(e,t=[],r,i){await this.write({lastCheckedTimestamp:Date.now(),latestVersion:e,blockedVersions:t,checkError:null,checkedAgainstVersion:r,checkedAgainstTag:i})}async writeError(e){let t=this.read();await this.write({...t,lastCheckedTimestamp:Date.now(),checkError:e})}getLatestVersion(){return this.read().latestVersion}getBlockedVersions(){return[...this.read().blockedVersions]}getCheckedAgainstVersion(){return this.read().checkedAgainstVersion}getCheckedAgainstTag(){return this.read().checkedAgainstTag}isCheckNeeded(){let{lastCheckedTimestamp:e}=this.read();if(!e||e>Date.now())return!0;let t=new Date().setHours(n.CHECK_WINDOW_HOUR,0,0,0),r=t>Date.now()?t-n.ONE_DAY_MS:t;return e<r}getLockPath(){return this.lockFilePath}read(){let e=Ec.get(this.cacheFilePath);if(e)return e;try{let t=ti.readFileSync(this.cacheFilePath,"utf-8"),r=JSON.parse(t);return Ec.set(this.cacheFilePath,r),r}catch{return{...iS}}}async write(e){m(()=>`Writing update cache: lastChecked=${e.lastCheckedTimestamp}, latest=${e.latestVersion}, blocked=[${e.blockedVersions.join(",")}], error=${e.checkError}`),await ti.promises.mkdir(ni.dirname(this.cacheFilePath),{recursive:!0}),await ti.promises.writeFile(this.cacheFilePath,JSON.stringify(e,null,2),"utf-8"),Ec.set(this.cacheFilePath,e)}};var ri=class{constructor(e){this.actionCommand=e}actionCommand;cache=new zt(qo.join(ut(),"update"));async checkAndNotify(){if(!this.shouldSkip())try{let e=Vt(),t=Qn(),r=this.cache.getCheckedAgainstVersion(),i=this.cache.getCheckedAgainstTag(),o=i!=null&&i!==t,s=r!=null&&r!==e,a=o?null:this.cache.getLatestVersion();a&&Vd(a,e)>0&&(console.log(),console.log(sS(`New version ${a} available, run \`devecocli update\` to upgrade`))),(o||s||this.cache.isCheckNeeded())&&await this.spawnBackgroundCheck()}catch(e){m(`Update check failed: ${e instanceof Error?e.message:String(e)}`)}}shouldSkip(){let e=this.actionCommand;for(;e;){if(e.name()==="update")return!0;e=e.parent}return!1}async spawnBackgroundCheck(){if(!process.argv[1]?.endsWith(".ts"))try{await cS(this.cache.getLockPath(),()=>{let e=[process.argv[1],"update","_check"];m(`Executing: ${process.execPath} ${e.join(" ")}`),oS(process.execPath,e,{detached:!0,stdio:["ignore","ignore","ignore"],env:{...process.env,DEVECO_CLI_SKIP_VERSION_CHECK:"1"}}).unref()})}catch{m("Update check lock held by another process, skipping")}}};async function cS(n,e){await sp.promises.mkdir(qo.dirname(n),{recursive:!0});let t=await aS.lock(n,{stale:6e4,retries:0,realpath:!1});try{await e()}finally{await t()}}var Cc=new lS("update").description("Update deveco-cli to latest");Cc.command("_check",{hidden:!0}).action(async()=>{let n=new zt(lp.join(ut(),"update"));try{let e=Qn(),t=zo();m(`Executing: npm view ${t}@${e} --json`);let{stdout:r}=await Pc("npm",["view",`${t}@${e}`,"--json"]),i=JSON.parse(r),o=typeof i.version=="string"?i.version.trim():null,s=Array.isArray(i.blockedVersions)?i.blockedVersions:[];await n.writeSuccess(o,s,Vt(),e)}catch(e){await n.writeError(e instanceof Error?e.message:String(e))}});Cc.action(async()=>{if(er()==="all")throw new Error("devecocli update is disabled (DEVECO_CLI_DISABLE_UPDATE=all).");let n=Vt(),e=Qn();console.log(bc("Checking for updates..."));let t=zo();try{let{stdout:r}=await Pc("npm",["view",t,`dist-tags.${e}`]),i=r.trim();if(!i||i===n){console.log(ap(`
|
|
49
|
+
${t} is already up to date (v${n}, tag: ${e})`));return}console.log(bc(`
|
|
50
|
+
New version found: ${i} (current: ${n})`)),console.log(bc(`Updating ${t}...`)),await Pc("npm",["install","-g",`${t}@${e}`],{stdio:"inherit"}),console.log(`
|
|
51
|
+
`+ap(`${t} updated successfully to version ${i}.`))}catch(r){let i=r;console.error(cp(`Failed to update ${t}`)),i.message&&console.error(cp(i.message)),process.exit(1)}});var dp=Cc;import{Command as HS}from"commander";import{execa as Jo}from"execa";function me(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as dS}from"child_process";var uS=2500;function pS(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function fS(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,uS);n.once("error",d=>c(d.message)),pS(n,l,s,a,c,o)}function up(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=dS(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),fS(s,o,r,i)})}import*as tr from"path";function mS(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function hS(n){let e=n.instancePath?.trim();if(e)return tr.dirname(tr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?tr.dirname(tr.normalize(t)).replace(/\\/g,"/"):""}function gS(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function pp(n,e){return e?[...n,"-bootmode",e]:n}function yS(n,e,t){let r=[pp(["-start",n],t)],i=hS(e);if(i)for(let o of gS(e.imageRoot))r.push(pp(["-hvd",n,"-path",i,...o],t));return mS(r)}async function fp(n,e,t,r){let i=new Error("No start strategy ran"),o=yS(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}function wS(n){let e=n.normalize("NFKC").match(/^\s*chargingStatus\s*:\s*(\d+)\s*$/im);if(!e)return;let t=Number(e[1]);if(t===1||t===3)return!0;if(t===0||t===2)return!1}async function Ic(n){return(await Z.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Bt)}async function Ac(n){let e=await Ic(n);return e.length===0?[]:(await Promise.all(e.map(r=>Mo(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function mp(n,e){return(await Ac(n)).includes(e)}async function hp(n,e){let t=await Z.withHdcPath(n).listDevicesWithName(),r=e.normalize("NFKC").replace(/\s+/g," ").trim(),i=t.find(a=>a.name.normalize("NFKC").replace(/\s+/g," ").trim()===r);if(!i||!Bt(i.serial))throw new Error(`Cannot resolve the running emulator serial for "${e}".`);let o=["-t",i.serial,"shell","hidumper","-s","3302","-a","-i"];m(`Executing: ${n} ${o.join(" ")}`);let s=await X(n,o);if(s.exitCode===0){let a=wS(s.stdout);if(a!==void 0)return a}throw new Error(`Cannot determine the battery charging state for emulator "${e}".`)}import*as rr from"path";import{existsSync as vS,statSync as SS}from"fs";function nr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function ES(n){let e=nr(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function bS(n){return nr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function PS(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=rr.dirname(rr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=rr.join(t,r.name);vS(i)&&SS(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function CS(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=bS(t),i=nr(t,["deviceType","DeviceType","devicetype"]),o=nr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:ES(t),path:nr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:nr(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function IS(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function gp(n){let t=CS(n)??IS(n);return PS(t),t}function Dc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function AS(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function DS(n){let e=Dc(n,["osVersion","OsVersion","OSVersion"]),t=Dc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Dc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function yp(n,e=()=>!0){let t=n.trim();if(!t)return[];try{let r=JSON.parse(t);if(!Array.isArray(r))return[];let i=[];for(let o of r){if(!o||typeof o!="object")continue;let s=o;if(!e(s))continue;let a=DS(s);a&&i.push(a)}return i}catch{return[]}}function wp(n){return yp(n)}function Yo(n){return yp(n,AS)}function vp(n){let t=Yo(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Sp=/no images are available/i,RS=/Scenario simulation failed\s*[::]/i,kS="7.0.0";function Ee(n){return n.normalize("NFKC").trim().toLowerCase()}function TS(n){let e=n.message||"";return Sp.test(e)}function xS(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function ii(n,e){return`${n} ${e.join(" ")}`.trim()}function NS(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var ir=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return m(`Executing: ${ii(this.emulatorPath,e)}`),Jo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return up(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return gp(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(me(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=me(e),i=t.find(a=>me(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await fp(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
52
|
+
Last error: ${s.lastError.message||"unknown"}`)}async isAlreadyRunning(e,t){return t?.isRunning===!0||t===void 0&&(await this.listEmulators()).find(i=>i.name===e)?.isRunning===!0?!0:mp(this.hdcPath,e)}async stopEmulator(e){let t=await this.listEmulators(),r=me(e),i=t.find(a=>me(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;return await this.isAlreadyRunning(o,i)?(await this.executeEmulator(["-stop",o]),"stopped"):"already-stopped"}async controlEmulator(e,t){await this.assertControlCommandSupported();let i=(await this.listEmulators()).find(s=>s.name===e);if(!i)throw new Error(`Emulator "${e}" not found.`);if(!await this.isAlreadyRunning(i.name,i))throw new Error(`Emulator "${e}" is not running.`);if(t.type==="battery"&&!await hp(this.hdcPath,i.name)&&t.level===0)throw new Error("Battery level must be an integer in [1, 100] while the emulator is not charging.");let o=this.buildControlArgs(i.name,t);m(`[EmulatorManager] control ${NS(t)} -> ${ii(this.emulatorPath,o)}`),await this.runEmulatorChecked(o,{extraReject:t.type==="folded-state"?[RS]:void 0,printOutputOnSuccess:!1})}async assertControlCommandSupported(){let e=this.emulatorPath;if(n.supportedControlPaths.has(e))return;let t=["-version"];m(`Executing: ${ii(this.emulatorPath,t)}`);let{stdout:r,stderr:i,exitCode:o}=await Jo(this.emulatorPath,t,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:1024*1024}),s=[r,i].filter(Boolean).join(`
|
|
53
|
+
`).trim(),a=xS(s);if(o!==0||!a)throw new Error("Emulator scene control commands require Emulator 7.0 or later. Unable to determine the current Emulator version.");if(A.compareVersion(a,kS)<0)throw new Error(`Emulator scene control commands require Emulator 7.0 or later. Current Emulator version is ${a}. Please upgrade DevEco Studio or the Emulator SDK.`);n.supportedControlPaths.add(e)}buildControlArgs(e,t){let r=["-instance",e];switch(t.type){case"shake":return[...r,"-shake"];case"power":return[...r,"-power"];case"rotation":return[...r,"-rotation",t.direction];case"volume":return[...r,"-volume",t.direction];case"folded-state":return[...r,"-foldedState",t.state];case"battery":return[...r,"-battery",String(t.level)];case"battery-status":return[...r,"-batteryStatus",String(t.status)];case"gps":return[...r,"-gps",`-${t.key}`,t.value];case"outdoor-running":return[...r,"-outdoorRunning"];case"outdoor-cycling":return[...r,"-outdoorCycling"];case"driving-navigation":return[...r,"-drivingNavigation"];case"sensor":return[...r,"-sensor",`-${t.key}`,String(t.value)];default:throw new Error(`Unknown emulator control action type: ${t.type}`)}}async executeEmulatorInherit(e){m(`Executing: ${ii(this.emulatorPath,e)}`);let{exitCode:t}=await Jo(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 hasAvailableEmulatorImage(e){let t=await this.listEmulatorImages({deviceType:e.deviceType}),r=Ee(e.deviceType),i=Ee(e.osVersion);return wp(t).some(o=>Ee(o.deviceType)===r&&Ee(o.osVersion)===i)}async uninstallEmulatorImage(e){let t=await this.resolveSoftwareVersionsForUninstall(e);if(t.length===0)throw new Error(`No downloaded image matches --os-version "${e.osVersion}" for --device-type "${e.deviceType}".`);let r;try{await this.runUninstallImageChecked(e.deviceType,e.osVersion)}catch(o){if(!TS(o))throw o;r=o}(r!==void 0||await this.hasMatchingDownloadedImage(e))&&await this.runSoftwareVersionFallback(e,t,r)}async listEmulatorImages(e){let t=["-imageList"];e.deviceType&&t.push("-deviceType",e.deviceType),e.downloaded!==void 0&&t.push("-downloaded",e.downloaded?"true":"false");let{stdout:r}=await this.executeEmulator(t);return r}async listDownloadedImageOsVersions(){let e=await this.listEmulatorImages({downloaded:!0});return vp(e)}async hasMatchingDownloadedImage(e){return(await this.findMatchingDownloadedImages(e)).length>0}async runSoftwareVersionFallback(e,t,r){try{for(let i of t)await this.runUninstallImageChecked(e.deviceType,i)}catch(i){let o=r!==void 0?`Primary uninstall failed: ${r.message}
|
|
54
|
+
`:"";throw new Error(`${o}Fallback uninstall failed: ${i.message}`,{cause:i})}if(await this.hasMatchingDownloadedImage(e))throw new Error(`Image for --device-type "${e.deviceType}" and --os-version "${e.osVersion}" remains listed as downloaded after uninstallation.`)}async resolveSoftwareVersionsForUninstall(e){let t=await this.findMatchingDownloadedImages(e);return[...new Set(t.map(r=>r.softwareVersion).filter(Boolean))]}async findMatchingDownloadedImages(e){let t=await this.listEmulatorImages({deviceType:e.deviceType,downloaded:!0}),r=Yo(t),i=Ee(e.deviceType),o=Ee(e.osVersion);return r.filter(s=>Ee(s.deviceType)===i&&(Ee(s.osVersion)===o||Ee(s.softwareVersion)===o))}async hasDownloadedSystemImage(e,t){let r=await this.listEmulatorImages({downloaded:!0}),i=Yo(r),o=Ee(t),s=e?.trim()?Ee(e):void 0;return i.some(a=>Ee(a.osVersion)===o||Ee(a.softwareVersion)===o?s===void 0?!0:Ee(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:[Sp]})}async runEmulatorChecked(e,t){m(`Executing: ${ii(this.emulatorPath,e)}`);let{stdout:r,stderr:i,exitCode:o}=await Jo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath},reject:!1,maxBuffer:20*1024*1024}),s=[r,i].filter(Boolean).join(`
|
|
55
55
|
`).trim(),a=/Invalid command|无效命令|鏃犳晥鍛戒护/i.test(s)||/please attach the correct parameter/i.test(s),c=(t?.extraReject??[]).some(d=>d.test(s));if(o!==0||a||c)throw new Error(s||`emulator exited with code ${o===null?"null":o}`);if(t?.printOutputOnSuccess!==!1&&s){let d=(t?.transformOutput?t.transformOutput(s):s).trim();d&&console.log(d)}}async checkExistingVirtualDevice(e,t){let r=await this.listEmulators(),i=me(e),o=r.find(s=>me(s.name)===i);if(o)if(t)await this.deleteVirtualDevice(o.name);else throw new Error(`Emulator "${e}" already exists. Use \`--force\` to overwrite.`);return i}async createVirtualDevice(e){let t=await this.checkExistingVirtualDevice(e.name,e.force),r=["-create",e.name,"-deviceType",e.deviceType,"-osVersion",e.osVersion];if(await this.runEmulatorChecked(r,{extraReject:[/Device create fail/i,/already exists/i,/Invalid OS version/i,/cannot be empty/i],printOutputOnSuccess:!0,transformOutput:o=>o.split(/\r?\n/).map(s=>s.trim().startsWith("Device create success.")?"Device create success.":s).join(`
|
|
56
56
|
`)}),!await this.waitForEmulatorPresenceByList(t))throw new Error(`Emulator "${e.name}" was reported as created, but it did not appear in the emulator list within the waiting period. Open the device manager list in DevEco Studio, then run this command again.`)}async waitForEmulatorPresenceByList(e,t=1e4,r=500){let i=Date.now()+t;for(;Date.now()<i;){if((await this.listEmulators()).some(a=>me(a.name)===e))return!0;await new Promise(a=>setTimeout(a,r))}return!1}async deleteVirtualDevice(e){let t=await this.listEmulators(),r=me(e),i=t.find(s=>me(s.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(i.isRunning===!0||await this.isAlreadyRunning(o,i))throw new Error(`Failed to delete device: ${o}
|
|
57
|
-
The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as
|
|
58
|
-
`)}function
|
|
57
|
+
The device may be running.`);return await this.runEmulatorChecked(["-delete",o,"-force"],{printOutputOnSuccess:!1}),o}};import{red as kc,yellow as Cp,gray as Ip}from"colorette";import $S from"ora";import{red as LS}from"colorette";function Ep(n,e){n?n.fail(e):console.error(LS(e)),process.exit(1)}import{green as OS}from"colorette";var MS=[[4352,4447],[9001,9002],[11904,42191],[43360,43388],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65281,65376],[65504,65510],[127744,129535],[131072,173791],[173824,177983],[177984,178207],[178208,183983],[183984,191456]],_S=[[0,31],[127,159],[768,879],[6832,6911],[7616,7679],[8203,8207],[8400,8447],[65024,65039],[65056,65071],[8205,8205]],FS=new RegExp("\x1B\\[([0-9;]*)[a-zA-Z]","g");function bp(n,e){for(let[t,r]of e)if(n>=t&&n<=r)return!0;return!1}function Rc(n){let e=n.replace(FS,""),t=0,r=0;for(;r<e.length;){let i=e.codePointAt(r);if(i===void 0)break;bp(i,_S)||(bp(i,MS)?t+=2:t+=1),r+=i>65535?2:1}return t}function Pp(n,e){let t=Rc(n);return n+" ".repeat(Math.max(0,e-t))}function jS(n,e){return n.map((t,r)=>{let i=Rc(t);for(let o of e){let s=o.cells[r]??"";i=Math.max(i,Rc(s))}return i})}function bt(n,e){let t=jS(n,e),r=[];r.push(n.map((i,o)=>Pp(i,t[o])).join(" ")),r.push(t.map(i=>"-".repeat(i)).join(" "));for(let i of e){let o=i.cells.map((s,a)=>Pp(s??"",t[a])).join(" ").trimEnd();r.push(i.highlight?OS(o):o)}return r.join(`
|
|
58
|
+
`)}function US(n,e){if(e.size!==0)for(let t of n){if(!t.isEmulator||!t.name)continue;let r=e.get(me(t.name));r&&(t.deviceType=r)}}var BS=["Name","Serial","Kind","Device Type"];function WS(n){return{cells:[n.name??n.serial,n.serial,n.isEmulator?"emulator":"device",n.deviceType??"-"],highlight:!0}}function GS(n,e){return n.isEmulator!==e.isEmulator?n.isEmulator?1:-1:(n.name??n.serial).localeCompare(e.name??e.serial)}function VS(){console.log(Cp(" No active devices.")),console.log(Ip(" Connect a USB device with debugging enabled, or start an emulator with `devecocli emulator start <name>`."))}function zS(n){let t=[...n].sort(GS).map(WS);console.log(bt(BS,t))}async function qS(n,e){if(!n.some(i=>i.isEmulator)||!e.emulatorPath)return;let r=await ir.from(e).getDeviceTypeByName();US(n,r)}async function YS(n,e,t){try{let r=await n.getConnectedEntries();await qS(r,e),t?.stop(),r.length===0?VS():zS(r)}catch(r){Ep(t,`Failed to list devices: ${r.message}`)}}async function JS(n,e){let t=await n.listDevices();if(!(t.length<2)){console.error(kc("Multiple devices connected. Specify a device with:"));for(let r of t){let i=await n.getDeviceName(r.serial);console.error(Ip(` ${e} -t ${r.serial} # ${i}`))}process.exit(1)}}async function KS(n,e){try{e||await JS(n,"devecocli device view");let t=await n.listDevices(),r=await n.getDeviceInfo(t,e);r||(console.log(Cp("No connected device found.")),process.exit(1));let i=await n.getDeviceDetail(r.serial),o=await n.getDeviceName(r.serial);console.log(` Serial: ${r.serial}`),console.log(` Device Name: ${o}`),i.deviceType&&console.log(` Device Type: ${i.deviceType}`),i.osVersion&&console.log(` OS Version: ${i.osVersion}`)}catch(t){console.error(kc(`Failed to show device details: ${t.message}`)),process.exit(1)}}async function Ap(){try{let n=await A.new();return{manager:Z.from(n),toolProvider:n}}catch(n){console.error(kc(`Failed to initialize device manager: ${n.message}`)),process.exit(1);return}}var Tc=new HS("device").description("Manage connected devices");Tc.command("list").description("List all connected devices").action(async()=>{let{manager:n,toolProvider:e}=await Ap(),t=$S({text:"Querying connected devices\u2026",color:"cyan"}).start();await YS(n,e,t)});Tc.command("view").description("Show detailed device information").option("-t, --target <serialOrName>","Target device serial or device name").action(async n=>{let{manager:e}=await Ap();await KS(e,n.target)});var Dp=Tc;import{Argument as Fc,Command as jc,Option as ar}from"commander";import{green as ci,cyan as sr,red as we,yellow as pt,gray as ai}from"colorette";import pE from"ora";import XS from"readline/promises";import{execa as kp}from"execa";import*as qt from"fs/promises";import*as Nc from"os";import*as Tn from"path";var xc=`1/4:\r
|
|
59
59
|
---------------------------------------\r
|
|
60
60
|
Statement About HarmonyOS and Privacy\r
|
|
61
61
|
\r
|
|
@@ -1225,13 +1225,13 @@ Part I: Chinese mainland.\r
|
|
|
1225
1225
|
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
|
|
1226
1226
|
\r
|
|
1227
1227
|
Part III: Other countries and regions.\r
|
|
1228
|
-
---------------------------------------\r`;var
|
|
1229
|
-
`),
|
|
1230
|
-
`)}function
|
|
1231
|
-
${t}.`);return
|
|
1232
|
-
`,"utf8"),!0}catch{}return!1}async function
|
|
1228
|
+
---------------------------------------\r`;var ZS=new Set,Ko=new Map,Lc="HarmonyOS_Software_Service_Agreement",Tp=["Emulator license agreements are not accepted yet.","","Accept the agreements interactively (shows full text + y/N prompt):"," devecocli emulator license","","Or accept non-interactively (no prompt, for CI/scripts):"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
|
|
1229
|
+
`),xp=Tp,Oc="HarmonyOS_SDK_Agreement";function Np(n,e){return`${n}\0${e}`}function Lp(){ZS.clear(),Ko.clear()}var QS=Tp,$e=class extends Error{constructor(e=QS){super(e),this.name="EmulatorLicenseBlockedError"}};function Op(n,e){return[n??"",e??""].join(`
|
|
1230
|
+
`)}function Mp(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 eE(n){return`Emulator${n.trim()}`}function _p(n){let e=eE(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 Tn.join(r,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Tn.join(Nc.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Tn.join(Nc.homedir(),".cache");return Tn.join(t,"Huawei",e,".emu_config")}async function tE(n,e,t){let r=Np(n,e),i=Ko.get(r);if(i!==void 0)return i;let o=await kp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Op(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new $e(t);return Ko.set(r,s),s}function nE(n){let e=n[0],t=n[n.length-1];return(e==='"'||e==="'")&&e===t?n.slice(1,-1):n}function rE(n){try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[r,i]of Object.entries(e))t[r]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function iE(n){let e=n.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let r=e.indexOf(t);if(r<=0)continue;let i=e.slice(0,r).trim();if(!i||t===":"&&i.includes("//"))continue;let o=nE(e.slice(r+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function oE(n){let e={};for(let t of n.split(/\r?\n/)){let r=iE(t);r&&(e[r.key]=r.entry)}return e}function sE(n){let e=n.trim();if(!e)return{};let t=rE(e);return t||oE(n)}function aE(n){return typeof n!="string"?!1:n.normalize("NFKC").trim().toLowerCase()==="agree"}async function Fp(n,e,t,r){let i=await tE(n,e,r),o=Mp(i);if(!o)throw new $e(r);let s=_p(o),a;try{a=await qt.readFile(s,"utf8")}catch(d){throw d.code==="ENOENT"?new $e(r):d}let l=sE(a)[t];if(!l)throw new $e(r);if(l.delimiter==="=")throw new $e(r);if(!aE(l.value))throw new $e(r)}async function Mc(n,e){await Fp(n,e,Lc,xp)}async function _c(n,e){await Fp(n,e,Oc,xp)}async function cE(n,e){let t=await kp(n,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),r=Op(t.stdout,t.stderr).trim();if(t.exitCode!==0||!r)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=Np(n,e);return Ko.set(i,r),r}async function jp(n,e){let t=await cE(n,e),r=Mp(t);if(!r)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1231
|
+
${t}.`);return _p(r)}function Rp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function lE(n,e,t){if(!t.startsWith("{"))return!1;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))return r[Lc]="agree",r[Oc]="agree",await qt.writeFile(n,`${JSON.stringify(r,null,2)}
|
|
1232
|
+
`,"utf8"),!0}catch{}return!1}async function dE(n,e){let t=Lc,r=Oc,i=[{k:t,re:new RegExp(`^\\s*${Rp(t)}\\s*[:=]`)},{k:r,re:new RegExp(`^\\s*${Rp(r)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let l=!1;for(let{k:d,re:g}of i)if(g.test(c)){s.push(`${d}:agree`),a.add(d),l=!0;break}l||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(r)||s.push(`${r}:agree`),await qt.writeFile(n,s.join(`
|
|
1233
1233
|
`)+(s.length>0?`
|
|
1234
|
-
`:""),"utf8")}async function
|
|
1234
|
+
`:""),"utf8")}async function Hp(n){await qt.mkdir(Tn.dirname(n),{recursive:!0});let e="";try{e=await qt.readFile(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}let t=e.trim();await lE(n,e,t)||await dE(n,e)}async function $p(n,e){return console.log(xc),0}var uE="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Up(n,e){try{return await Mc(n,e),await _c(n,e),!0}catch(t){if(t instanceof $e)return!1;throw t}}async function Bp(n,e){if(await Up(n,e))return console.log("Emulator license agreements are already accepted."),0;if(console.log(xc),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("`devecocli emulator license` requires an interactive terminal.\nFor non-interactive environments, use: devecocli emulator license accept"),1;let r=XS.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await r.question(uE)}finally{r.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return console.error("Agreements not accepted. Emulator features will remain blocked until accepted."),1;try{let s=await jp(n,e);await Hp(s),Lp()}catch(s){return console.error(s.message),1}return console.log("Emulator license agreements accepted."),0}async function Wp(n,e){if(await Up(n,e))return console.log("Emulator license agreements are already accepted."),0;try{let t=await jp(n,e);await Hp(t),Lp()}catch(t){return console.error(t.message),1}return console.log("Emulator license agreements accepted."),0}var fE=["ohos.qemu.hvd.name","const.product.name","const.product.model"],Gp=["open","half-open","close","vertical-open","single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"],mE=`
|
|
1235
1235
|
Folded state scene mappings:
|
|
1236
1236
|
foldableFold (3):
|
|
1237
1237
|
open Fully expanded state
|
|
@@ -1254,43 +1254,43 @@ Folded state scene mappings:
|
|
|
1254
1254
|
left-half-folded-right-folded
|
|
1255
1255
|
left-expanded-right-half-folded
|
|
1256
1256
|
left-half-folded-right-half-folded
|
|
1257
|
-
`;function aE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function cE(n){let e=n.trim();if(!$p.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${$p.join(", ")}`);return e}function Bp(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function Wp(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!lE(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function lE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function dE(n,e,t,r,i){return Number(Wp(n,e,t,r,i))}function uE(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 pE(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 fE(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(ft("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(ft("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(we("--os-version does not match any downloaded image (exact string required).")),console.log(ft("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var mE=["Name","Status","Serial","Device Type","OS Version"];function hE(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function gE(n,e){let t=await Promise.all(e.map(async r=>{let i=await Jn(n,r,oE);return[r,i]}));return new Map(t)}async function yE(n){let e=await Cc(n),t=await gE(n,e);return{serials:e,params:t}}function wE(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function vE(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&wE(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function SE(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(({emu:i,serial:o,effectiveRunning:s})=>({name:i.name,status:s?"running":"stopped",serial:o??null,deviceType:i.deviceType??null,osVersion:i.osVersion??null}))}async function EE(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),yE(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":ft(" No emulator instances found."));return}let s=i.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=vE(o.serials,o.params,s);r?.stop();let l=SE(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(hE);console.log(Pt(mE,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Gp(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(we(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(ai(s.stdout)),s.stderr&&console.error(ai(s.stderr))}return r}var bE=2e3,PE=6e4;async function CE(n,e){let t=me(e);return(await Ic(n)).some(i=>me(i)===t)}async function Vp(n,e,t,r=PE,i=bE){let o=Date.now()+r;for(;Date.now()<o;){if(await CE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function IE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(ft(`Emulator "${t}" is already running.`));return}console.log(sr(`Starting emulator "${t}"...`));let i=await Vp(e,t,!0);console.log(i?ci(`Emulator "${t}" started successfully.`):ft(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function AE(n,e,t){let r=await Promise.allSettled(t.map(o=>IE(n,e,o)));Gp(r,t,"start")&&process.exit(1)}async function zp(n,e){let t=e.trim();if(!Bt(t))return t;let r=await Q.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function DE(n,e,t){let r=await zp(e,t);if(console.log(sr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(ft(`Emulator "${r}" is already stopped.`));return}let o=await Vp(e,r,!1);console.log(o?ci(`Emulator "${r}" stopped successfully.`):ft(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function RE(n,e,t){let r=await Promise.allSettled(t.map(o=>DE(n,e,o)));Gp(r,t,"stop")&&process.exit(1)}async function Ue(){try{let n=await I.new();return{manager:ir.from(n),toolProvider:n}}catch(n){console.error(we(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Ct(n,e){try{let t=aE(n.target),r=e(),{manager:i,toolProvider:o}=await Ue(),s=await zp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(ci(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(we(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function kE(n){let e=[];return Xo(e,"longitude",n.longitude,-180,180,8),Xo(e,"latitude",n.latitude,-90,90,8),Xo(e,"altitude",n.altitude,-1e4,1e4,2),Xo(e,"bearing",n.direction,0,359.99,2,"--direction"),Fc(e,"Specify one geolocation option.")}function TE(n){let e=[];return oi(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),oi(e,"humidity",n.humidity,0,100,!1),oi(e,"temperature",n.temperature,-273.1,100,!1),oi(e,"steps",n.steps,0,1e4,!0),oi(e,"heartrate",n.heartrate,0,255,!0),Fc(e,"Specify one sensor option.")}function Fc(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function Xo(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:Wp(s,t,r,i,o)})}function oi(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?Bp(s,t,r,i):dE(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function xE(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:Bp("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Fc(e,"Specify --level or --status.")}var le=new _c("emulator").description("Manage emulator instances"),LE=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Zo(n){let e=new ar("--device-type <type>","Emulator device type").choices([...LE]);return n?e.makeOptionMandatory():e}function or(n,e){for(let t of e)if(t in n)return n[t]}function si(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Up(n){let e=si(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var NE=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],OE="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function qp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Yp(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=si(or(i,["osVersion","OsVersion","OSVersion","os_version"])),s=si(or(i,["deviceType","DeviceType","device_type"])),a=Up(or(i,["downloaded","Downloaded","isDownloaded"])),c=si(or(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=si(or(i,["releaseType","ReleaseType","release_type"])),d=Up(or(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function ME(n){let e=n.trim();if(!e)return!0;let t=qp(e);return t===null?!1:t.length===0?!0:Yp(t,!0).length===0}function _E(n,e){let t=n.trim();if(!t)return"";let r=qp(t);if(!r)return n.trimEnd();let i=Yp(r,e);return Pt(NE,i)}var Qo=new _c("image").description("HarmonyOS emulator system images (download, list, remove)");Qo.command("download").description("Download system image").addOption(Zo(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await Ue();try{await Oc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof $e&&(console.error(we(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(we("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(we("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(we(`Failed to download system image: ${r.message}`)),process.exit(1)}});Qo.command("remove").description("Remove a downloaded system image").addOption(Zo(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ue();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(we(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Qo.command("list").description("List system images").addOption(Zo(!1)).option("--all","List all images (local and remote)").addOption(new ar("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ue();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(ME(r)){console.log(ft(OE));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=_E(r,n.all===!0);console.log(i)}catch(t){console.error(we(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});le.addCommand(Qo);var es=new _c("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");es.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ue(),e=await _p(n.emulatorPath,n.sdkPath);process.exit(e)});es.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ue(),e=await Hp(n.emulatorPath,n.sdkPath);process.exit(e)});es.action(async()=>{let{toolProvider:n}=await Ue(),e=await jp(n.emulatorPath,n.sdkPath);process.exit(e)});le.addCommand(es);le.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ct(n,()=>({type:"shake"})));le.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Ct(n,()=>({type:"power"})));le.command("rotate").description("Rotate emulator").addOption(new ar("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Mc("<direction>").choices(["left","right"])).action((n,e)=>Ct(e,()=>({type:"rotation",direction:n})));le.command("volume").description("Change volume").addOption(new ar("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Mc("<direction>").choices(["up","down"])).action((n,e)=>Ct(e,()=>({type:"volume",direction:n})));le.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",sE).action((n,e)=>Ct(e,()=>({type:"folded-state",state:cE(n)})));le.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new ar("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Ct(n,()=>xE(n)));le.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Ct(n,()=>kE(n)));le.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Mc("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Ct(e,()=>t[n])});le.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Ct(n,()=>TE(n)));le.command("list").description("List all emulator instances").addOption(new ar("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e,toolProvider:t}=await Ue(),r=n.format==="table"?iE({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await EE(e,t.hdcPath,n.format,r)});le.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ue();try{await Nc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof $e&&(console.error(we(r.message)),process.exit(1)),r}n?.length||(console.error(we("Error: missing required argument 'names'")),process.exit(1)),await AE(e,t.hdcPath,n)});le.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await Ue();n?.length||(console.error(we("Error: missing required argument 'names'")),process.exit(1)),await RE(e,t.hdcPath,n)});var Jp=le.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(Zo(!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");Jp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1258
|
-
${
|
|
1257
|
+
`;function hE(n){let e=n.trim();if(!e)throw new Error("--target must not be empty.");return e}function gE(n){let e=n.trim();if(!Gp.includes(e))throw new Error(`Invalid fold state "${n}". Available values: ${Gp.join(", ")}`);return e}function zp(n,e,t,r){let i=e.trim();if(!/^-?\d+$/.test(i))throw new Error(`${n} must be an integer in [${t}, ${r}].`);let o=Number(i);if(o<t||o>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function qp(n,e,t,r,i){let o=e.trim(),s=Number(o);if(!o||Number.isNaN(s))throw new Error(`${n} must be a number in [${t}, ${r}].`);if(i!==void 0&&!yE(o,i))throw new Error(`${n} supports at most ${i} decimal place(s).`);if(s<t||s>r)throw new Error(`${n} must be in [${t}, ${r}].`);return o}function yE(n,e){let t=n.split(".")[1];return t===void 0||t.length<=e}function wE(n,e,t,r,i){return Number(qp(n,e,t,r,i))}function vE(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 SE(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 EE(n,e){let t=i=>i.normalize("NFKC").trim(),r=t(n);if(e.length===0)throw console.error(pt("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(pt("Run `devecocli emulator image download ...` followed by `devecocli emulator image list` and then copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===r)){console.error(we("--os-version does not match any downloaded image (exact string required).")),console.log(pt("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${n}".`)}}var bE=["Name","Status","Serial","Device Type","OS Version"];function PE(n){return{cells:[n.name,n.status,n.serial??"-",n.deviceType??"-",n.osVersion??"-"],highlight:n.status==="running"}}async function CE(n,e){let t=await Promise.all(e.map(async r=>{let i=await Jn(n,r,fE);return[r,i]}));return new Map(t)}async function IE(n){let e=await Ic(n),t=await CE(n,e);return{serials:e,params:t}}function AE(n,e,t,r,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,n);let c=r.indexOf(n);c!==-1&&r.splice(c,1);return}}function DE(n,e,t){let r=new Map,i=new Map,o=[...n],s=[...t];for(let a of n){let c=e.get(a),l=c?.get("ohos.qemu.hvd.name");l&&i.set(l,a),t.length>0&&AE(a,c,s,o,r)}for(let a=0;a<s.length&&a<o.length;a++)r.set(s[a],o[a]);return{productSerialMap:r,hvdSerialMap:i}}function RE(n,e,t){let r=n.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return r.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),r.map(({emu:i,serial:o,effectiveRunning:s})=>({name:i.name,status:s?"running":"stopped",serial:o??null,deviceType:i.deviceType??null,osVersion:i.osVersion??null}))}async function kE(n,e,t,r){try{let[i,o]=await Promise.all([n.listEmulators(),IE(e)]);if(i.length===0){r?.stop(),console.log(t==="json"?"[]":pt(" No emulator instances found."));return}let s=i.filter(g=>g.isRunning).map(g=>g.name),{productSerialMap:a,hvdSerialMap:c}=DE(o.serials,o.params,s);r?.stop();let l=RE(i,a,c);if(t==="json"){console.log(JSON.stringify(l,null,2));return}let d=l.map(PE);console.log(bt(bE,d))}catch(i){throw r?.stop(),new Error(`Failed to list emulators: ${i.message}`,{cause:i})}}function Yp(n,e,t){let r=!1;for(let i=0;i<n.length;i++){let o=n[i];if(o.status!=="rejected")continue;r=!0;let s=o.reason;console.error(we(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(ai(s.stdout)),s.stderr&&console.error(ai(s.stderr))}return r}var TE=2e3,xE=6e4;async function NE(n,e){let t=me(e);return(await Ac(n)).some(i=>me(i)===t)}async function Jp(n,e,t,r=xE,i=TE){let o=Date.now()+r;for(;Date.now()<o;){if(await NE(n,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function LE(n,e,t){if(await n.startEmulator(t)==="already-running"){console.log(pt(`Emulator "${t}" is already running.`));return}console.log(sr(`Starting emulator "${t}"...`));let i=await Jp(e,t,!0);console.log(i?ci(`Emulator "${t}" started successfully.`):pt(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function OE(n,e,t){let r=await Promise.allSettled(t.map(o=>LE(n,e,o)));Yp(r,t,"start")&&process.exit(1)}async function Kp(n,e){let t=e.trim();if(!Bt(t))return t;let r=await Z.withHdcPath(n).getDeviceName(t);if(r===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return r}async function ME(n,e,t){let r=await Kp(e,t);if(console.log(sr(`Stopping emulator "${r}"...`)),await n.stopEmulator(r)==="already-stopped"){console.log(pt(`Emulator "${r}" is already stopped.`));return}let o=await Jp(e,r,!1);console.log(o?ci(`Emulator "${r}" stopped successfully.`):pt(`Emulator "${r}" stop signal was sent but the instance is still visible in hdc list targets within the waiting period.`))}async function _E(n,e,t){let r=await Promise.allSettled(t.map(o=>ME(n,e,o)));Yp(r,t,"stop")&&process.exit(1)}async function Ue(){try{let n=await A.new();return{manager:ir.from(n),toolProvider:n}}catch(n){console.error(we(`Failed to initialize emulator: ${n.message}`)),process.exit(1);return}}async function Pt(n,e){try{let t=hE(n.target),r=e(),{manager:i,toolProvider:o}=await Ue(),s=await Kp(o.hdcPath,t);await i.controlEmulator(s,r),console.log(ci(`Emulator "${t}" operation completed.`))}catch(t){let r=n.target?.trim()||"<unknown>";console.error(we(`Failed to operate emulator "${r}": ${t.message}`)),process.exit(1)}}function FE(n){let e=[];return Xo(e,"longitude",n.longitude,-180,180,8),Xo(e,"latitude",n.latitude,-90,90,8),Xo(e,"altitude",n.altitude,-1e4,1e4,2),Xo(e,"bearing",n.direction,0,359.99,2,"--direction"),Hc(e,"Specify one geolocation option.")}function jE(n){let e=[];return oi(e,"light",n.lightIntensity,0,1e5,!1,"--light-intensity"),oi(e,"humidity",n.humidity,0,100,!1),oi(e,"temperature",n.temperature,-273.1,100,!1),oi(e,"steps",n.steps,0,1e4,!0),oi(e,"heartrate",n.heartrate,0,255,!0),Hc(e,"Specify one sensor option.")}function Hc(n,e){if(n.length===0)throw new Error(e);if(n.length>1)throw new Error("Only one operation option can be specified.");return n[0]}function Xo(n,e,t,r,i,o,s=`--${e}`){t!==void 0&&n.push({type:"gps",key:e,value:qp(s,t,r,i,o)})}function oi(n,e,t,r,i,o,s=`--${e}`){if(t===void 0)return;let a=o?zp(s,t,r,i):wE(s,t,r,i,1);n.push({type:"sensor",key:e,value:a})}function HE(n){let e=[];return n.level!==void 0&&e.push({type:"battery",level:zp("--level",n.level,0,100)}),n.status!==void 0&&e.push({type:"battery-status",status:n.status==="charging"?1:0}),Hc(e,"Specify --level or --status.")}var le=new jc("emulator").description("Manage emulator instances"),$E=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Zo(n){let e=new ar("--device-type <type>","Emulator device type").choices([...$E]);return n?e.makeOptionMandatory():e}function or(n,e){for(let t of e)if(t in n)return n[t]}function si(n){return n==null?"":typeof n=="string"?n.trim():String(n).trim()}function Vp(n){let e=si(n).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var UE=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],BE="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";async function WE(n,e,t){if(!await n.hasAvailableEmulatorImage({deviceType:e,osVersion:t}))throw new Error(`Option '--os-version <version>' argument '${t}' is invalid. The version entered is incorrect; download is not possible.`)}function Xp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e:null}catch{return null}}function Zp(n,e){let t=[];for(let r of n){if(!r||typeof r!="object")continue;let i=r,o=si(or(i,["osVersion","OsVersion","OSVersion","os_version"])),s=si(or(i,["deviceType","DeviceType","device_type"])),a=Vp(or(i,["downloaded","Downloaded","isDownloaded"])),c=si(or(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),l=si(or(i,["releaseType","ReleaseType","release_type"])),d=Vp(or(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,l,d,a],highlight:e&&a==="true"})}return t}function GE(n){let e=n.trim();if(!e)return!0;let t=Xp(e);return t===null?!1:t.length===0?!0:Zp(t,!0).length===0}function VE(n,e){let t=n.trim();if(!t)return"";let r=Xp(t);if(!r)return n.trimEnd();let i=Zp(r,e);return bt(UE,i)}var Qo=new jc("image").description("HarmonyOS emulator system images (download, list, remove)");Qo.command("download").description("Download system image").addOption(Zo(!1)).option("--os-version <version>","Example: HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async n=>{let{manager:e,toolProvider:t}=await Ue();try{await _c(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof $e&&(console.error(we(r.message)),process.exit(1)),r}n.deviceType?.trim()||(console.error(we("Error: missing required option '--device-type <type>'")),process.exit(1)),n.osVersion?.trim()||(console.error(we("Error: misssing required option '--os-version <version>'")),process.exit(1)),await WE(e,n.deviceType.trim(),n.osVersion.trim());try{await e.installEmulatorImage({deviceType:n.deviceType.trim(),osVersion:n.osVersion.trim(),force:n.force===!0})}catch(r){console.error(we(`Failed to download system image: ${r.message}`)),process.exit(1)}});Qo.command("remove").description("Remove a downloaded system image").addOption(Zo(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async n=>{let{manager:e}=await Ue();try{await e.uninstallEmulatorImage({deviceType:n.deviceType,osVersion:n.osVersion})}catch(t){console.error(we(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Qo.command("list").description("List system images").addOption(Zo(!1)).option("--all","List all images (local and remote)").addOption(new ar("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e}=await Ue();try{let t;n.all?t=void 0:t=!0;let r=await e.listEmulatorImages({deviceType:n.deviceType,downloaded:t});if(GE(r)){console.log(pt(BE));return}if(n.format==="json"){console.log(r.trimEnd());return}let i=VE(r,n.all===!0);console.log(i)}catch(t){console.error(we(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});le.addCommand(Qo);var es=new jc("license").description("Review and accept emulator license agreements interactively (prints full text + y/N prompt)");es.command("view").description("Review agreement text (read-only, no changes)").action(async()=>{let{toolProvider:n}=await Ue(),e=await $p(n.emulatorPath,n.sdkPath);process.exit(e)});es.command("accept").description("Accept all emulator license agreements non-interactively (skips review and prompt)").action(async()=>{let{toolProvider:n}=await Ue(),e=await Wp(n.emulatorPath,n.sdkPath);process.exit(e)});es.action(async()=>{let{toolProvider:n}=await Ue(),e=await Bp(n.emulatorPath,n.sdkPath);process.exit(e)});le.addCommand(es);le.command("shake").description("Trigger shake event").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Pt(n,()=>({type:"shake"})));le.command("power").description("Press power button (toggle screen on/off)").requiredOption("--target <nameOrSerial>","Target emulator name or serial").action(n=>Pt(n,()=>({type:"power"})));le.command("rotate").description("Rotate emulator").addOption(new ar("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Fc("<direction>").choices(["left","right"])).action((n,e)=>Pt(e,()=>({type:"rotation",direction:n})));le.command("volume").description("Change volume").addOption(new ar("--target <nameOrSerial>","Target emulator name or serial").makeOptionMandatory()).addArgument(new Fc("<direction>").choices(["up","down"])).action((n,e)=>Pt(e,()=>({type:"volume",direction:n})));le.command("fold <state>").description("Set foldable display state").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addHelpText("after",mE).action((n,e)=>Pt(e,()=>({type:"folded-state",state:gE(n)})));le.command("battery").description("Set battery level or charging status").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--level <0-100>","Battery level, SOC (charging: 0-100; not charging: 1-100)").addOption(new ar("--status <status>","Charging status").choices(["charging","discharging"])).action(n=>Pt(n,()=>HE(n)));le.command("geolocation").description("Inject geographic coordinates and direction").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--longitude <value>","Longitude (-180.0 to 180.0)").option("--latitude <value>","Latitude (-90.0 to 90.0)").option("--altitude <value>","Altitude (-10000.0 to 10000.0)").option("--direction <value>","Heading direction in degrees (0.00 to 359.99)").action(n=>Pt(n,()=>FE(n)));le.command("scene").description("Start motion simulation scene").requiredOption("--target <nameOrSerial>","Target emulator name or serial").addArgument(new Fc("<type>","Motion simulation scene").choices(["outdoorRunning","outdoorCycling","drivingNavigation"])).action((n,e)=>{let t={outdoorRunning:{type:"outdoor-running"},outdoorCycling:{type:"outdoor-cycling"},drivingNavigation:{type:"driving-navigation"}};return Pt(e,()=>t[n])});le.command("sensor").description("Inject sensor data").requiredOption("--target <nameOrSerial>","Target emulator name or serial").option("--light-intensity <value>","Light sensor (0 to 100000)").option("--humidity <value>","Humidity sensor (0 to 100)").option("--temperature <value>","Temperature sensor (-273.1 to 100)").option("--steps <value>","Steps sensor (integer 0 to 10000)").option("--heartrate <value>","Heart rate sensor (integer 0 to 255)").action(n=>Pt(n,()=>jE(n)));le.command("list").description("List all emulator instances").addOption(new ar("--format <format>","Output format").choices(["table","json"]).default("table")).action(async n=>{let{manager:e,toolProvider:t}=await Ue(),r=n.format==="table"?pE({text:"Listing emulators\u2026",color:"cyan"}).start():void 0;await kE(e,t.hdcPath,n.format,r)});le.command("start [names...]").description("Start one or more emulator instances").action(async n=>{let{manager:e,toolProvider:t}=await Ue();try{await Mc(t.emulatorPath,t.sdkPath)}catch(r){throw r instanceof $e&&(console.error(we(r.message)),process.exit(1)),r}n?.length||(console.error(we("Error: missing required argument 'names'")),process.exit(1)),await OE(e,t.hdcPath,n)});le.command("stop <names...>").description("Stop one or more emulator instances (by name or serial,e.g.,127.0.0.1:<port>)").action(async n=>{let{manager:e,toolProvider:t}=await Ue();n?.length||(console.error(we("Error: missing required argument 'names'")),process.exit(1)),await _E(e,t.hdcPath,n)});var Qp=le.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(Zo(!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");Qp.configureOutput({outputError:(n,e)=>{e(n),/too many arguments/i.test(n)&&e(`
|
|
1258
|
+
${pt("Tip: ")}${ai("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1259
1259
|
${sr('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1260
1260
|
${sr('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1261
|
-
`)}});Jp.action(async(n,e)=>{try{uE(n),pE(e.osVersion);let{manager:t}=await Ue(),r=await t.listDownloadedImageOsVersions();fE(e.osVersion,r),console.log(sr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(ci(`Emulator "${n}" created successfully.`))}catch(t){console.error(we(`${t.message}`)),process.exit(1)}});le.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ue();console.log(sr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(ci(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(we(r.message)),r.stdout&&console.error(ai(r.stdout)),r.stderr&&console.error(ai(r.stderr)),process.exit(1)}});var Kp=le;import{Command as eb}from"commander";import{red as Wc,cyan as We}from"colorette";import*as vf from"readline";import*as gf from"crypto";import*as Xp from"http";import*as Zp from"crypto";import{URL as FE}from"url";var ts=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=Xp.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new FE(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;if(e.method==="POST"){let a="";e.on("data",c=>{a+=c.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,s,a)})}else this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&Zp.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as be from"fs";import*as lr from"path";import{homedir as GE}from"os";var At={};Yy(At,{LocalCrypto:()=>At,decryptForLocalStorage:()=>UE,decryptForLocalStorageFromDirectory:()=>BE,encryptForLocalStorage:()=>$E,isEncryptedBlob:()=>WE});import*as q from"fs";import*as It from"path";import*as Ee from"crypto";import*as ef from"os";import{homedir as tf}from"os";var mt=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var li=vn.ALGORITHM,nf=vn.IV_LENGTH,di=vn.KEY_LENGTH,ui=vn.KEY_LENGTH,pi=vn.KEK_VERSIONS,ns=process.env.DEVECO_CLI_DATA_DIR||It.join(tf(),fe.CONFIG_DIR_NAME,fe.APP_NAME),rs=It.join(tf(),".local","share",fe.APP_NAME,"keys"),cr=It.join(ns,fe.KEY_FILE_NAME);function Qp(n){return ef.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function jc(n){return It.join(rs,`${n}.bin`)}function rf(){if(!q.existsSync(ns))try{q.mkdirSync(ns,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new mt(Qp(ns)):n}if(!q.existsSync(rs))try{q.mkdirSync(rs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new mt(Qp(It.dirname(rs))):n}}function of(){rf();for(let n of pi){let e=jc(n);q.existsSync(e)||q.writeFileSync(e,Ee.randomBytes(di),{mode:384})}}function sf(n){of();let e=jc(n),t=q.readFileSync(e);if(t.length===di)return t;let r=Ee.randomBytes(di);return q.writeFileSync(e,r,{mode:384}),r}function Hc(n,e){let t=Ee.randomBytes(nf),r=sf(e),i=Ee.createCipheriv(li,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:li,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function af(n,e){return cf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function cf(n,e,t,r){let i=Ee.createDecipheriv(li,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function lf(n,e){return cf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function jE(){if(of(),q.existsSync(cr))return;let n=Ee.randomBytes(ui),e=Hc(n,pi[0]);q.writeFileSync(cr,JSON.stringify(e,null,2),{mode:384})}function df(){jE();let n=JSON.parse(q.readFileSync(cr,"utf8")),e=af(n,sf(n.kekId));if(e.length===ui)return e;let t=Ee.randomBytes(ui),r=Hc(t,pi[0]);return q.writeFileSync(cr,JSON.stringify(r,null,2),{mode:384}),t}function HE(){rf();for(let t of pi){let r=jc(t);q.existsSync(r)||q.writeFileSync(r,Ee.randomBytes(di),{mode:384})}if(q.existsSync(cr))return;let n=Ee.randomBytes(ui),e=Hc(n,pi[0]);q.writeFileSync(cr,JSON.stringify(e,null,2),{mode:384})}function $E(n){let e=df(),t=Ee.randomBytes(nf),r=Ee.createCipheriv(li,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:li,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function UE(n){try{return lf(n,df())}catch{throw HE(),new Error("Failed to decrypt local ciphertext")}}function BE(n,e){let t=It.join(e,fe.KEY_FILE_NAME),r=JSON.parse(q.readFileSync(t,"utf8")),i=It.join(e,"keys",`${r.kekId}.bin`),o=q.readFileSync(i);if(o.length!==di)throw new Error("Invalid external root key");let s=af(r,o);if(s.length!==ui)throw new Error("Invalid external data encryption key");return lf(n,s)}function WE(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function et(){return process.env.DEVECO_CLI_AUTH_SOURCE===fe.AUTH_SOURCE_DEVECO_CODE}var is=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||lr.join(GE(),fe.CONFIG_DIR_NAME,fe.APP_NAME);return lr.join(e,fe.TOKEN_FILE_NAME)}ensureConfigDir(){let e=lr.dirname(this.getLocalTokenFilePath());be.existsSync(e)||be.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=At.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();be.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return et()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!et())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=lr.join(e,fe.TOKEN_FILE_NAME);if(!be.existsSync(t))return null;let r=JSON.parse(be.readFileSync(t,"utf8"));return At.isEncryptedBlob(r)?At.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!be.existsSync(e))return null;let t=JSON.parse(be.readFileSync(e,"utf8"));return At.isEncryptedBlob(t)?At.decryptForLocalStorage(t):null}catch{return await this.clearToken(),null}}async clearToken(){if(et())throw new Error("Current session is managed by DevEco Code. Cannot modify via CLI.");let e=this.getLocalTokenFilePath();try{be.existsSync(e)&&be.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Be=new is;var ht={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},fi={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},os={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},VE={[ht.CHINA]:fi.CHINA,[ht.RUSSIA]:fi.RUSSIA,[ht.EUROPE]:fi.EUROPE,[ht.SINGAPORE]:fi.CHINA},zE={[os.CHINA]:ht.CHINA,[os.SINGAPORE]:ht.SINGAPORE,[os.EUROPE]:ht.EUROPE,[os.RUSSIA]:ht.RUSSIA};function uf(n){return VE[n]??fi.CHINA}function pf(n){return zE[n]??ht.CHINA}function ss(n,e){return n?.toUpperCase()===ht.CHINA?Je.CN_LOGIN_URL:e}import{exec as qE}from"child_process";import{promisify as YE}from"util";var JE=YE(qE);async function ff(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;default:t=`xdg-open "${n}"`;break}try{await JE(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import KE from"axios";var $c=class{client;constructor(){let e={timeout:Gr.HTTP_TIMEOUT_MS,headers:{"User-Agent":fo.USER_AGENT,"accept-language":fo.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=KE.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}
|
|
1262
|
-
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},
|
|
1263
|
-
`)}function nb(){return new Promise(n=>{let e=vf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var hi=new eb("auth").description("Authentication commands (login, logout, status, team)");hi.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(et()){console.log(Wc("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{if(await ie.isLoggedIn()){let t=await ie.getUserInfo();if(t){console.log(We(`Already logged in, User Name:${t.userName}`));return}}console.log(We("Starting login process...")),console.log(We("Press Enter to open browser for login...")),await nb();let e=await ie.login();console.log(We(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof mt?n:new Error("Login failed",{cause:n})}});hi.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(et()){console.log(Wc("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await ie.logout();console.log(n?We("Logout successful"):We("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});hi.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await ie.isLoggedIn()){console.log(We("Not logged in"));return}let e=await ie.getUserInfo();if(!e){console.log(We("Not logged in"));return}console.log(We(`Current user: ${e.userName}`))}catch{console.log(We("Not logged in"))}});var rb=hi.command("team").description("Team-related commands");rb.command("list").description("List team accounts the current user has joined").action(async()=>{try{if(!await ie.isLoggedIn()){et()?console.log(Wc("Not logged in. Please login via DevEco Code first.")):console.log(We("Please run `devecocli auth login` first."));return}let e=await Yt();console.log(tb(e.teamList))}catch(n){throw new Error("Failed to list teams",{cause:n})}});var Sf=hi;import{Command as wb}from"commander";import{green as vb,red as Si,cyan as Wf,yellow as Gf,dim as Vf}from"colorette";import Sb from"p-limit";import ib from"ora";var tt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=ib(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 Ef from"fs";import*as bf from"path";import{homedir as ob}from"os";var Pf=["DevEco"];async function ds(){let n=await L.get(Ke.TAGS_API_URL),t=us(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 sb(n){let e=[],t=Ke.DEFAULT_PAGE_SIZE,r=1;for(;;){let i=await L.post(Ke.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:r,pageSize:t,tagIds:[n]}}),o=us(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;r++}return e}async function Gc(n){let e=new Map,t=n.map(i=>sb(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Pf.includes(o.name)))}async function ab(n,e){let t=await L.post(Ke.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Ke.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return us(t,"Skills API").data.list}async function Vc(n,e){let t=new Map,r=e.map(o=>ab(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Pf.includes(s.name)))}function Cf(n){let e=[];for(let[,t]of Object.entries(Xe)){let r=bf.join(ob(),t.path,n);Ef.existsSync(r)&&e.push(t.displayName)}return e.sort()}function us(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=L.parseJson(n);if(t.code!==Ke.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function If(n){let e=`${Ke.SKILL_API_BASE}/${n}/checksum`,t=await L.get(e);return us(t,"Checksum API").data}import cb from"adm-zip";import lb from"crypto";import Df from"fs";import J from"path";import{fileURLToPath as db}from"url";import{homedir as Rf}from"os";import{red as ub}from"colorette";var Dt=Df.promises;function zc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Af(n,e){let t=J.resolve(e),r=J.resolve(n),i=J.relative(r,t);if(i.startsWith("..")||J.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function qc(n){return J.isAbsolute(n)?n:J.resolve(process.cwd(),n)}function pb(n){return lb.createHash("sha256").update(n).digest("hex")}async function fb(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=pb(n),i=e.sha256.toLowerCase();if(r!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function kf(n){let e=`${Ke.SKILL_API_BASE}/${n}/install?format=zip`,t=await L.getBinary(e),r=await If(n);return await fb(t,r),t}async function mb(n,e,t){zc(t);let r=new cb(n),i=r.getEntries();try{await Dt.stat(e)}catch{await Dt.mkdir(e,{recursive:!0})}let o=J.join(e,t);Af(e,o);for(let s of i){let a=J.join(o,s.entryName);Af(o,a)}r.extractAllTo(o,!0)}async function Yc(n){let e=Xe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Xe).join(", ")}`);let t=J.join(Rf(),e.path.replace("/skills",""));try{return await Dt.access(t),!0}catch{return!1}}function Jc(n){let e=Xe[n];return J.join(Rf(),e.path)}function hb(n){let e=Xe[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Xe).join(", ")}`);return e}function Kc(n,e){let t=hb(e),r="projectPath"in t?t.projectPath:J.join("."+e,"skills");return J.join(n,r)}async function gb(n,e,t){zc(e);let r=J.join(n,e);try{if(await Dt.access(r),t)await Dt.rm(r,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${n}.`),{skillDir:r,shouldSkip:!0}}catch{}return{skillDir:r,shouldSkip:!1}}async function Xc(n,e,t){await mb(n,e,t),console.log(`Skill ${t} installed to ${J.join(e,t)}.`)}async function Zc(n,e,t){let r=J.join(e,t);await Dt.mkdir(r,{recursive:!0});let i=J.join(r,J.basename(n));await Dt.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Tf(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(ub(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function dr(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await gb(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Tf(n,i,"Installation failed")}}async function Qc(n,e){try{zc(n);let t=await e(),r=J.join(t,n);try{await Dt.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await Dt.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Tf(n,t,"Removal failed")}}async function xf(n,e,t,r=!1){return dr(n,()=>Jc(e),i=>Xc(t,i,n),r)}async function Lf(n,e,t,r=!1){return dr(n,()=>t,i=>Xc(e,i,n),r)}async function Nf(n,e,t,r,i=!1){return dr(n,()=>Kc(t,r),o=>Xc(e,o,n),i)}async function Of(n,e,t,r=!1){return dr(n,()=>Jc(t),i=>Zc(e,i,n),r)}async function Mf(n,e,t,r,i=!1){return dr(n,()=>Kc(t,r),o=>Zc(e,o,n),i)}async function _f(n,e,t,r=!1){return dr(n,()=>t,i=>Zc(e,i,n),r)}async function Ff(n,e){return Qc(n,()=>Jc(e))}async function jf(n,e){return Qc(n,()=>e)}async function Hf(n,e,t){return Qc(n,()=>Kc(e,t))}function $f(){let e=J.dirname(db(import.meta.url));for(;;){let t=J.join(e,"SKILL.md");if(Df.existsSync(t))return t;let r=J.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Uf from"fs";import{cyan as yb}from"colorette";async function gi(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Yc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function yi(){let n=[];for(let e of Object.keys(Xe))await Yc(e)&&n.push(e);return n}function wi(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(yb("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Jt(n,e,t){if(!Uf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Uf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function vi(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?qc(n):void 0,resolvedProject:e?qc(e):void 0}}async function ps(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await gi(n.agent)).map(a=>({project:t,agent:a})):t?i=(await yi()).map(a=>({project:t,agent:a})):n.agent?r=await gi(n.agent):r=await yi(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function Eb(n){let e=await ds();if(n.all)return(await Gc(e)).map(r=>r.enName);{let r=(await Vc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function bb(n,e,t,r){let i=[];if(t.customPath){let o=await Lf(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await xf(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Nf(n,e,o,s,r);i.push(a)}return i}function Pb(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}=vi(n.path,n.project,n.agent);return t&&Jt(t,"Project directory",n.force),e&&Jt(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Cb(n,e,t){let r=await ps(n,e,t);return{skillNames:await Eb(n),targets:r}}async function Ib(n,e,t,r){let i=[],o=n.length,s=Sb(5),a=n.map(c=>s(()=>Ab(c)));for(let c=0;c<n.length;c++){let l=n[c],d=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${d}...`);let g=await a[c];if(!g.success){r.fail(),console.log(Si(`${l}: Download failed - ${g.error}`)),i.push({success:!1});continue}r.stop();let w=await bb(l,g.buffer,e,t);i.push(...w)}return i}async function Ab(n){try{let e=await kf(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 Db(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Pb(n),{skillNames:i,targets:o}=await Cb(n,t,r),s=await Ib(i,o,n.force||!1,e);e.stop(),wi(s)}catch(t){throw e.stop(),t}}function Rb(n){let{resolvedPath:e,resolvedProject:t}=vi(n.path,n.project,n.agent);return t&&Jt(t,"Project directory"),e&&Jt(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function kb(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=Rb(e);t.stop();let o=await Tb(e,n,r,i);t.stop(),wi(o)}catch(r){throw t.stop(),r}}function Bf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function fs(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Ff(n,r.agent):await Hf(n,r.project,r.agent);t.push(i)}return t}async function Tb(n,e,t,r){if(t)return[await jf(e,t)];if(r&&n.agent){let a=(await gi(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return fs(e,a)}if(r){let s=await yi();Bf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return fs(e,a)}if(n.agent){let a=(await gi(n.agent)).map(c=>({type:"agent",agent:c}));return fs(e,a)}let i=await yi();Bf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return fs(e,o)}var Ei=new wb("skills").description("Manage HarmonyOS skills");Ei.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 ds(),r=await Gc(t);if(r.length===0){e.stop(),console.log(Gf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(Wf(i.enName)),console.log(Vf(i.description));let o=Cf(i.enName);o.length>0&&console.log(vb(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(Si(t.message)),process.exit(1)}});Ei.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new tt;try{e.start("Searching skills...");let t=await ds(),r=await Vc(n,t);if(r.length===0){console.log(Gf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(Wf(i.enName)),console.log(Vf(i.description)),console.log()}catch(t){e.stop(),console.error(Si(t.message)),process.exit(1)}});Ei.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 Db(n)}catch(e){console.error(Si(e.message)),process.exit(1)}});Ei.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 kb(n.skill,n)}catch(e){console.error(Si(e.message)),process.exit(1)}});var zf=Ei;import{Command as Lb,InvalidArgumentError as nl}from"commander";import{cyan as ms}from"colorette";function xn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Yn(t);return r==="transient"?new Error(`${e}: Device communication channel unavailable. Retry in a few seconds.`):r==="fatal"?new Error(`${e}: ${t.trim()}`):null}var el=[800,1500,2500];function xb(n){return new Promise(e=>setTimeout(e,n))}var ur=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Q.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1261
|
+
`)}});Qp.action(async(n,e)=>{try{vE(n),SE(e.osVersion);let{manager:t}=await Ue(),r=await t.listDownloadedImageOsVersions();EE(e.osVersion,r),console.log(sr(`Creating emulator "${n}"...`)),await t.createVirtualDevice({name:n,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(ci(`Emulator "${n}" created successfully.`))}catch(t){console.error(we(`${t.message}`)),process.exit(1)}});le.command("delete <name>").description("Delete a local emulator instance").action(async n=>{let{manager:e}=await Ue();console.log(sr(`Deleting emulator "${n}"...`));try{let t=await e.deleteVirtualDevice(n);console.log(ci(`Emulator "${t}" deleted successfully.`))}catch(t){let r=t;console.error(we(r.message)),r.stdout&&console.error(ai(r.stdout)),r.stderr&&console.error(ai(r.stderr)),process.exit(1)}});var ef=le;import{Command as lb}from"commander";import{red as Vc,cyan as We}from"colorette";import*as Pf from"readline";import*as Sf from"crypto";import*as tf from"http";import*as nf from"crypto";import{URL as zE}from"url";var ts=class{server=null;port=0;clientSecret;callbackPath="/callback";resolveCallback=null;rejectCallback=null;timeoutId=null;baseUrl;successRedirectUrl;failedRedirectUrl;constructor(e,t,r,i){this.clientSecret=e,this.baseUrl=t,this.successRedirectUrl=r,this.failedRedirectUrl=i}async start(){return new Promise((e,t)=>{let r=tf.createServer((i,o)=>{this.handleRequest(i,o)});r.keepAliveTimeout=1,r.on("error",i=>{t(new Error("Failed to start local auth server",{cause:i}))}),r.listen(0,"127.0.0.1",()=>{this.server=r;let i=r.address();this.port=i.port,e()})})}async waitForCallback(e=3e4){return new Promise((t,r)=>{this.resolveCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),t(i)},this.rejectCallback=i=>{this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),r(i)},this.timeoutId=setTimeout(()=>{this.timeoutId=null,this.rejectCallback?.(new Error("Callback timeout"))},e)})}async stop(){return this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server?new Promise(e=>{let t=this.server;this.server=null,typeof t.closeAllConnections=="function"&&t.closeAllConnections();let r=setTimeout(()=>{e()},100);t.close(()=>{clearTimeout(r),e()})}):Promise.resolve()}handleRequest(e,t){let r=e.headers.host||"";if(![`127.0.0.1:${this.port}`,`localhost:${this.port}`].includes(r.toLowerCase())){t.writeHead(400),t.end("Bad Host");return}let o=new zE(e.url??"",`http://${r}`);if(o.pathname!==this.callbackPath){t.writeHead(404),t.end("Not Found");return}try{let s=o.searchParams;if(e.method==="POST"){let a="";e.on("data",c=>{a+=c.toString()}),e.on("end",()=>{this.handleCallbackRequest(e,t,s,a)})}else this.handleCallbackRequest(e,t,s,"")}catch(s){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(s)}}handleCallbackRequest(e,t,r,i){try{let o=this.parseParams(r,i),s=o.get("code"),a=o.get("tempToken"),c=o.get("siteId"),l=o.get("quit");if(!this.validateCode(s)){t.writeHead(400),t.end("Bad Request");return}if(this.isQuitRequest(l)){this.handleQuitRequest(t);return}if(!a||!c){t.writeHead(400),t.end("Bad Request");return}let d={tempToken:a,siteId:c,quit:l??void 0};this.resolveCallback?.(d),this.sendSuccessResponse(t)}catch(o){t.writeHead(500),t.end("Internal Server Error"),this.rejectCallback?.(o)}}parseParams(e,t){return t&&t.trim()?new URLSearchParams(t):e}validateCode(e){let t=Buffer.from(e||"","utf8"),r=Buffer.from(this.clientSecret,"utf8");return t.length===r.length&&nf.timingSafeEqual(t,r)}isQuitRequest(e){return e==="true"||e==="access_denied"||e==="quit"}handleQuitRequest(e){this.rejectCallback?.(new Error("User quit the login process")),e.writeHead(302,{Location:`${this.baseUrl}/${this.failedRedirectUrl}`}),e.end()}sendSuccessResponse(e){e.writeHead(302,{Location:`${this.baseUrl}/${this.successRedirectUrl}`}),e.end()}getPort(){return this.port}};import*as Pe from"fs";import*as lr from"path";import{homedir as QE}from"os";var It={};Zy(It,{LocalCrypto:()=>It,decryptForLocalStorage:()=>KE,decryptForLocalStorageFromDirectory:()=>XE,encryptForLocalStorage:()=>JE,isEncryptedBlob:()=>ZE});import*as q from"fs";import*as Ct from"path";import*as be from"crypto";import*as of from"os";import{homedir as sf}from"os";var ft=class extends Error{constructor(e){super(e),this.name="DefinedError"}};var li=vn.ALGORITHM,af=vn.IV_LENGTH,di=vn.KEY_LENGTH,ui=vn.KEY_LENGTH,pi=vn.KEK_VERSIONS,ns=process.env.DEVECO_CLI_DATA_DIR||Ct.join(sf(),fe.CONFIG_DIR_NAME,fe.APP_NAME),rs=Ct.join(sf(),".local","share",fe.APP_NAME,"keys"),cr=Ct.join(ns,fe.KEY_FILE_NAME);function rf(n){return of.platform()==="win32"?`Permission denied. Please run as administrator or grant write permission to ${n}.`:`Permission denied. You can try: sudo chown -R $(whoami) ${n}`}function $c(n){return Ct.join(rs,`${n}.bin`)}function cf(){if(!q.existsSync(ns))try{q.mkdirSync(ns,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ft(rf(ns)):n}if(!q.existsSync(rs))try{q.mkdirSync(rs,{recursive:!0,mode:448})}catch(n){throw n.code==="EACCES"?new ft(rf(Ct.dirname(rs))):n}}function lf(){cf();for(let n of pi){let e=$c(n);q.existsSync(e)||q.writeFileSync(e,be.randomBytes(di),{mode:384})}}function df(n){lf();let e=$c(n),t=q.readFileSync(e);if(t.length===di)return t;let r=be.randomBytes(di);return q.writeFileSync(e,r,{mode:384}),r}function Uc(n,e){let t=be.randomBytes(af),r=df(e),i=be.createCipheriv(li,r,t),o=Buffer.concat([i.update(n),i.final()]),s=i.getAuthTag();return{version:1,algorithm:li,kekId:e,encryptedDek:o.toString("base64"),iv:t.toString("base64"),authTag:s.toString("base64"),timeStamp:Date.now()}}function uf(n,e){return pf(Buffer.from(n.encryptedDek,"base64"),e,n.iv,n.authTag)}function pf(n,e,t,r){let i=be.createDecipheriv(li,e,Buffer.from(t,"base64"));return i.setAuthTag(Buffer.from(r,"base64")),Buffer.concat([i.update(n),i.final()])}function ff(n,e){return pf(Buffer.from(n.ciphertext,"base64"),e,n.iv,n.authTag).toString("utf8")}function qE(){if(lf(),q.existsSync(cr))return;let n=be.randomBytes(ui),e=Uc(n,pi[0]);q.writeFileSync(cr,JSON.stringify(e,null,2),{mode:384})}function mf(){qE();let n=JSON.parse(q.readFileSync(cr,"utf8")),e=uf(n,df(n.kekId));if(e.length===ui)return e;let t=be.randomBytes(ui),r=Uc(t,pi[0]);return q.writeFileSync(cr,JSON.stringify(r,null,2),{mode:384}),t}function YE(){cf();for(let t of pi){let r=$c(t);q.existsSync(r)||q.writeFileSync(r,be.randomBytes(di),{mode:384})}if(q.existsSync(cr))return;let n=be.randomBytes(ui),e=Uc(n,pi[0]);q.writeFileSync(cr,JSON.stringify(e,null,2),{mode:384})}function JE(n){let e=mf(),t=be.randomBytes(af),r=be.createCipheriv(li,e,t),i=Buffer.concat([r.update(n,"utf8"),r.final()]),o=r.getAuthTag();return{version:1,algorithm:li,ciphertext:i.toString("base64"),iv:t.toString("base64"),authTag:o.toString("base64"),timeStamp:Date.now()}}function KE(n){try{return ff(n,mf())}catch{throw YE(),new Error("Failed to decrypt local ciphertext")}}function XE(n,e){let t=Ct.join(e,fe.KEY_FILE_NAME),r=JSON.parse(q.readFileSync(t,"utf8")),i=Ct.join(e,"keys",`${r.kekId}.bin`),o=q.readFileSync(i);if(o.length!==di)throw new Error("Invalid external root key");let s=uf(r,o);if(s.length!==ui)throw new Error("Invalid external data encryption key");return ff(n,s)}function ZE(n){if(!n||typeof n!="object")return!1;let e=n;return e.algorithm==="aes-256-gcm"&&typeof e.ciphertext=="string"&&typeof e.iv=="string"&&typeof e.authTag=="string"}function et(){return process.env.DEVECO_CLI_AUTH_SOURCE===fe.AUTH_SOURCE_DEVECO_CODE}var is=class{getLocalTokenFilePath(){let e=process.env.DEVECO_CLI_DATA_DIR||lr.join(QE(),fe.CONFIG_DIR_NAME,fe.APP_NAME);return lr.join(e,fe.TOKEN_FILE_NAME)}ensureConfigDir(){let e=lr.dirname(this.getLocalTokenFilePath());Pe.existsSync(e)||Pe.mkdirSync(e,{recursive:!0,mode:448})}async saveJwtToken(e){if(!e)throw new Error("Token is empty");let t=It.encryptForLocalStorage(e);this.ensureConfigDir();let r=this.getLocalTokenFilePath();Pe.writeFileSync(r,JSON.stringify(t,null,2),{mode:384})}async loadJwtToken(){return et()?this.loadDevecoCodeToken():this.loadLocalJwtToken()}loadDevecoCodeToken(){if(!et())return null;let e=process.env.DEVECO_CODE_AUTH_DIR?.trim();if(!e)return null;try{let t=lr.join(e,fe.TOKEN_FILE_NAME);if(!Pe.existsSync(t))return null;let r=JSON.parse(Pe.readFileSync(t,"utf8"));return It.isEncryptedBlob(r)?It.decryptForLocalStorageFromDirectory(r,e):null}catch{return null}}async loadLocalJwtToken(){let e=this.getLocalTokenFilePath();try{if(!Pe.existsSync(e))return null;let t=JSON.parse(Pe.readFileSync(e,"utf8"));return It.isEncryptedBlob(t)?It.decryptForLocalStorage(t):null}catch{return await this.clearToken(),null}}async clearToken(){if(et())throw new Error("Current session is managed by DevEco Code. Cannot modify via CLI.");let e=this.getLocalTokenFilePath();try{Pe.existsSync(e)&&Pe.unlinkSync(e)}catch(t){throw new Error("Failed to clear token",{cause:t})}}},Be=new is;var mt={CHINA:"CN",RUSSIA:"RU",SINGAPORE:"SG",EUROPE:"EU"},fi={CHINA:"zh_CN",RUSSIA:"ru_RU",EUROPE:"de_DE"},os={CHINA:"1",SINGAPORE:"5",EUROPE:"7",RUSSIA:"8"},eb={[mt.CHINA]:fi.CHINA,[mt.RUSSIA]:fi.RUSSIA,[mt.EUROPE]:fi.EUROPE,[mt.SINGAPORE]:fi.CHINA},tb={[os.CHINA]:mt.CHINA,[os.SINGAPORE]:mt.SINGAPORE,[os.EUROPE]:mt.EUROPE,[os.RUSSIA]:mt.RUSSIA};function hf(n){return eb[n]??fi.CHINA}function gf(n){return tb[n]??mt.CHINA}function ss(n,e){return n?.toUpperCase()===mt.CHINA?Je.CN_LOGIN_URL:e}import{exec as nb}from"child_process";import{promisify as rb}from"util";var ib=rb(nb);async function yf(n){let e=process.platform,t;switch(e){case"win32":t=`start "" "${n}"`;break;case"darwin":t=`open "${n}"`;break;default:t=`xdg-open "${n}"`;break}try{await ib(t)}catch(r){throw new Error("Failed to open browser",{cause:r})}}import ob from"axios";var Bc=class{client;constructor(){let e={timeout:Gr.HTTP_TIMEOUT_MS,headers:{"User-Agent":fo.USER_AGENT,"accept-language":fo.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=ob.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}
|
|
1262
|
+
${r}`)})}async get(e,t){let r=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}async post(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(r)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,statusText:e.statusText??"",headers:e.headers}}parseJson(e){try{return JSON.parse(e.data)}catch(t){throw new Error(`Failed to parse JSON response: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async getBinary(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(r.status!==200)throw new Error(`HTTP ${r.status}`);return Buffer.from(r.data)}async postAllowFailure(e,t){let r=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async deleteAllowFailure(e,t){let r=await this.client.request({method:"DELETE",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0});return this.convertResponse(r)}async getBinaryAllowFailure(e,t){let r=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout,validateStatus:()=>!0}),i=Buffer.from(r.data),o=i.toString("utf8");return{statusCode:r.status,statusText:r.statusText??"",buffer:i,body:o}}},N=new Bc;var Wc=class{async checkJwtToken(e,t,r){let i={refresh:"false",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:i});if(a.statusCode!==200)throw new Error(`Failed to check jwtToken: ${a.statusCode}`);return N.parseJson(a)}async refreshToken(e,t){let r=await Be.loadJwtToken();return r?this.refreshTokenWithToken(r,e,t):null}async refreshTokenWithToken(e,t,r){try{let i={refresh:"true",jwtToken:e},s=`${t()}/${r}`,a=await N.get(s,{headers:i});if(a.statusCode!==200)return null;let c=N.parseJson(a);return!c.status||!c.userInfo?null:{accessToken:c.userInfo.accessToken,refreshToken:c.userInfo.refreshToken??""}}catch(i){let o=i;return console.error(`Failed to refresh token: ${o.code??""} ${o.message??""}`),null}}},mi=new Wc;function wf(n){try{let e=n.split(".");if(e.length!==3)return null;let r=e[1].replace(/-/g,"+").replace(/_/g,"/"),i=r.padEnd(r.length+(4-r.length%4)%4,"="),o=Buffer.from(i,"base64").toString("utf8");return JSON.parse(o)}catch{return null}}function vf(n){let e=n.split(".");return e.length===3&&e.every(t=>t.length>0)}var Gc=class{async getJwtToken(e,t,r,i,o){let s=e.split("&")[0],a=gf(t),c=r(),l={tempToken:s,site:a,version:fe.API_VERSION,appid:o},d=`${c}/${i}`,g=await N.get(d,{params:l});if(g.statusCode!==200)throw new Error(`Failed to get jwtToken: status=${g.statusCode}`);let w=g.data.trim();if(!vf(w))throw new Error("Invalid jwtToken format");return w}async getUserInfoFromJwt(e,t){let r=await t(e);if(!r.status||!r.userInfo)throw new Error("Invalid jwtToken");let i=wf(e);if(!i)throw new Error("Invalid jwtToken: failed to parse payload");return{userId:i.userId,userName:i.userName,accessToken:r.userInfo.accessToken,refreshToken:r.userInfo.refreshToken??"",jwtToken:e,countryCode:r.userInfo.nationalCode,language:hf(r.userInfo.nationalCode),isRealName:String(r.userInfo.realName)==="true"}}},as=new Gc;var cs=class{config;server=null;constructor(e){this.config={...Vr,...e}}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}async login(){try{m(`Login started, isDevecoCodeAuth: ${et()}`);let e=this.generateClientSecret();this.server=new ts(e,this.getRegionalizedBaseUrl(),this.config.successRedirectUrl,this.config.failedRedirectUrl),await this.server.start(),m(`Local auth server started on port ${this.server.getPort()}`),await this.openLoginPage(this.server.getPort(),e),m("Browser opened for authentication");let t=await this.server.waitForCallback(this.config.timeout);if(m(`Callback received: siteId=${t.siteId}`),t.siteId!=="1")throw new ft("Non-China accounts are not supported.");let r=await as.getJwtToken(t.tempToken,t.siteId,()=>this.getRegionalizedBaseUrl(),this.config.tempTokenCheckUrl,this.config.appId);m("JWT token received");let i=await as.getUserInfoFromJwt(r,o=>mi.checkJwtToken(o,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl));return m(`User info received: ${i.userName}`),await Be.saveJwtToken(r),m("JWT token saved"),i}finally{this.server&&(await this.server.stop(),this.server=null)}}async isLoggedIn(){let e=await Be.loadJwtToken();return e?(await mi.checkJwtToken(e,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)).status?!0:(et()||await Be.clearToken(),!1):!1}async logout(){let e=await Be.loadJwtToken();if(!e)return!1;let r=`${this.getRegionalizedBaseUrl()}/${this.config.logoutUrl}?jwtToken=${e}`;try{await N.post(r,{timeout:5e3})}finally{await Be.clearToken()}return!0}async getUserInfo(){let e=await Be.loadJwtToken();return e?as.getUserInfoFromJwt(e,t=>mi.checkJwtToken(t,()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)):null}generateClientSecret(){return Sf.randomUUID().replace(/-/g,"")}getRegionalizedBaseUrl(){return ss(this.config.countryCode??"",this.config.baseUrl)}async openLoginPage(e,t){let i=`${this.getRegionalizedBaseUrl()}/${this.config.authUrl}?port=${e}&appid=${this.config.appId}&code=${t}`;await yf(i)}async refreshToken(){return mi.refreshToken(()=>this.getRegionalizedBaseUrl(),this.config.jwtTokenCheckUrl)}},re=new cs;import Ef from"axios";var ab="No JWT in local storage. Run `devecocli auth login` first.";function cb(n){if(n==null||typeof n!="object")return[];let e=n;if(e.ret&&e.ret.code!==0)throw new Error(`team list request failed: code=${e.ret.code}${e.ret.msg?`, msg=${e.ret.msg}`:""}`);return Array.isArray(e.teams)?e.teams.filter(t=>typeof t=="object"&&t!==null).map(t=>({id:String(t.id??""),upSiteId:Number(t.upSiteId??0),name:String(t.name??""),countryCode:String(t.countryCode??""),siteId:Number(t.siteId??0),userType:Number(t.userType??0),lastLoginTime:String(t.lastLoginTime??""),isMirror:t.isMirror===!0})).filter(t=>t.id.length>0):[]}var ls=class{config;constructor(e){this.config={...Vr,...e}}updateConfig(e){this.config={...this.config,...e}}async listTeams(){let e=await Be.loadJwtToken();if(!e)throw new Error(ab);let{accessToken:t,userId:r}=await this.fetchAccessToken(e);if(!t)throw new Error("Session expired. Run `devecocli auth login` again.");let i=await this.fetchTeamList(t,r??""),o=cb(i);return{userId:r??"",teamList:o}}async fetchTeamList(e,t){let r=this.config.agcTeamListUrl;m(`Executing: GET ${r}`);let i;try{i=await Ef.request({method:"GET",url:r,headers:{oauth2Token:e,uid:t,source:"cli",lang:"zh_CN"},timeout:15e3,transformResponse:[o=>o],proxy:!1,validateStatus:()=>!0})}catch(o){throw new Error(`Network error while listing teams: ${o.message}`,{cause:o})}if(i.status===401)throw new Error("AGC rejected the AGC token. Run `devecocli auth login` again.");if(i.status!==200)throw new Error(`Failed to list teams: HTTP ${i.status}`);return typeof i.data=="string"?JSON.parse(i.data):i.data}async fetchAccessToken(e){let r=`${this.getRegionalizedBaseUrl()}/${this.config.jwtTokenCheckUrl}`;m(`Executing: GET ${r} (accessToken refresh)`);let i;try{i=await Ef.request({method:"GET",url:r,headers:{refresh:"true",jwtToken:e},timeout:15e3,transformResponse:[a=>a],proxy:!1,validateStatus:()=>!0})}catch(a){throw new Error(`Network error while refreshing accessToken: ${a.message}`,{cause:a})}if(i.status!==200)throw new Error(`Failed to refresh accessToken: HTTP ${i.status}. Run \`devecocli auth login\` again.`);let s=typeof i.data=="string"?JSON.parse(i.data):i.data;if(!s.status)throw new Error("JWT is invalid. Run `devecocli auth login` again.");return{accessToken:s.userInfo?.accessToken,userId:s.userInfo?.userId}}getRegionalizedBaseUrl(){return ss(this.config.countryCode??"",this.config.baseUrl)}},bf=new ls;async function Yt(){return bf.listTeams()}function db(n){if(n.length===0)return We("No teams found for the current user.");let e=["Id","Name"],t=n.map(s=>[s.id,s.name]),r=e.map((s,a)=>Math.max(s.length,...t.map(c=>c[a].length))),i=s=>s.map((a,c)=>a.padEnd(r[c])).join(" "),o=r.map(s=>"-".repeat(s)).join(" ");return[i(e),o,...t.map(i)].join(`
|
|
1263
|
+
`)}function ub(){return new Promise(n=>{let e=Pf.createInterface({input:process.stdin,output:process.stdout});e.question("",()=>{e.close(),n()})})}var hi=new lb("auth").description("Authentication commands (login, logout, status, team)");hi.command("login").description("Log in to your Huawei Developer account").action(async()=>{if(et()){console.log(Vc("Login is managed by DevEco Code. Login from DevEco Code instead."));return}try{if(await re.isLoggedIn()){let t=await re.getUserInfo();if(t){console.log(We(`Already logged in, User Name:${t.userName}`));return}}console.log(We("Starting login process...")),console.log(We("Press Enter to open browser for login...")),await ub();let e=await re.login();console.log(We(`Login successful. Logged in as ${e.userName}.`))}catch(n){throw n instanceof ft?n:new Error("Login failed",{cause:n})}});hi.command("logout").description("Log out of your Huawei Developer account").action(async()=>{if(et()){console.log(Vc("Login is managed by DevEco Code. Log out from DevEco Code instead."));return}try{let n=await re.logout();console.log(n?We("Logout successful"):We("Already logged out."))}catch(n){throw new Error("Logout failed",{cause:n})}});hi.command("status").description("Show the currently logged-in user").action(async()=>{try{if(!await re.isLoggedIn()){console.log(We("Not logged in"));return}let e=await re.getUserInfo();if(!e){console.log(We("Not logged in"));return}console.log(We(`Current user: ${e.userName}`))}catch{console.log(We("Not logged in"))}});var pb=hi.command("team").description("Team-related commands");pb.command("list").description("List team accounts the current user has joined").action(async()=>{try{if(!await re.isLoggedIn()){et()?console.log(Vc("Not logged in. Please login via DevEco Code first.")):console.log(We("Please run `devecocli auth login` first."));return}let e=await Yt();console.log(db(e.teamList))}catch(n){throw new Error("Failed to list teams",{cause:n})}});var Cf=hi;import{Command as Rb}from"commander";import{green as kb,red as Si,cyan as qf,yellow as Yf,dim as Jf}from"colorette";import Tb from"p-limit";import fb from"ora";var tt=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=fb(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 If from"fs";import*as Af from"path";import{homedir as mb}from"os";var Df=["DevEco"];async function ds(){let n=await N.get(Oe.TAGS_API_URL),t=us(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 hb(n){let e=[],t=Oe.DEFAULT_PAGE_SIZE,r=Oe.DEFAULT_MAX_PAGES,i=1;for(;i<=r;){let o=await N.post(Oe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:i,pageSize:t,tagIds:[n]}}),s=us(o,"Skills API");if(e.push(...s.data.list),s.data.list.length<t)break;i++}return e}async function zc(n){let e=new Map,t=n.map(i=>hb(i)),r=await Promise.all(t);for(let i of r)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values()).filter(i=>i.tags?.every(o=>!Df.includes(o.name)))}async function gb(n,e){let t=await N.post(Oe.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Oe.DEFAULT_PAGE_SIZE,keyword:n,tagIds:[e]}});return us(t,"Skills API").data.list}async function qc(n,e){let t=new Map,r=e.map(o=>gb(n,o)),i=await Promise.all(r);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values()).filter(o=>o.tags?.every(s=>!Df.includes(s.name)))}function Rf(n){let e=[];for(let[,t]of Object.entries(Ke)){let r=Af.join(mb(),t.path,n);If.existsSync(r)&&e.push(t.displayName)}return e.sort()}function us(n,e){if(n.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${n.statusCode}`);let t=N.parseJson(n);if(t.code!==Oe.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function kf(n){let e=`${Oe.SKILL_API_BASE}/${n}/checksum`,t=await N.get(e);return us(t,"Checksum API").data}import yb from"adm-zip";import wb from"crypto";import{timingSafeEqual as vb}from"crypto";import xf from"fs";import J from"path";import{fileURLToPath as Sb}from"url";import{homedir as Nf}from"os";import{red as Eb}from"colorette";var At=xf.promises;function Yc(n){if(!/^[A-Za-z0-9._-]+$/.test(n)||n==="."||n==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(n)}`)}function Tf(n,e){let t=J.resolve(e),r=J.resolve(n),i=J.relative(r,t);if(i.startsWith("..")||J.isAbsolute(i))throw new Error(`Path traversal detected: ${e}.`)}function Jc(n){return J.isAbsolute(n)?n:J.resolve(process.cwd(),n)}function bb(n){return wb.createHash("sha256").update(n).digest("hex")}async function Pb(n,e){if(n.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let r=bb(n),i=e.sha256.toLowerCase(),o=Buffer.from(r,"hex"),s=Buffer.from(i,"hex");if(o.length!==s.length||!vb(o,s))throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function Lf(n){let e=`${Oe.SKILL_API_BASE}/${n}/install?format=zip`,t=await N.getBinary(e),r=await kf(n);return await Pb(t,r),t}async function Cb(n,e,t){Yc(t);let r=new yb(n),i=r.getEntries();try{await At.stat(e)}catch{await At.mkdir(e,{recursive:!0})}let o=J.join(e,t);Tf(e,o);for(let s of i){let a=J.join(o,s.entryName);Tf(o,a)}r.extractAllTo(o,!0)}async function Kc(n){let e=Ke[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Ke).join(", ")}`);let t=J.join(Nf(),e.path.replace("/skills",""));try{return await At.access(t),!0}catch{return!1}}function Xc(n){let e=Ke[n];return J.join(Nf(),e.path)}function Ib(n){let e=Ke[n];if(!e)throw new Error(`Invalid agent: ${n}, Valid options are: ${Object.keys(Ke).join(", ")}`);return e}function Zc(n,e){let t=Ib(e),r="projectPath"in t?t.projectPath:J.join("."+e,"skills");return J.join(n,r)}async function Ab(n,e,t){Yc(e);let r=J.join(n,e);try{if(await At.access(r),t)await At.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 Qc(n,e,t){await Cb(n,e,t),console.log(`Skill ${t} installed to ${J.join(e,t)}.`)}async function el(n,e,t){let r=J.join(e,t);await At.mkdir(r,{recursive:!0});let i=J.join(r,J.basename(n));await At.copyFile(n,i),console.log(`Skill ${t} installed to ${r}.`)}function Of(n,e,t=""){let r=e instanceof Error?e.message:t;return console.log(Eb(`Faild to exute operation for skill "${n}": ${r}`)),{success:!1,error:r}}async function dr(n,e,t,r){try{let i=await e(),{shouldSkip:o}=await Ab(i,n,r);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return Of(n,i,"Installation failed")}}async function tl(n,e){try{Yc(n);let t=await e(),r=J.join(t,n);try{await At.access(r)}catch{return console.log(`Skill ${n} not found in ${t}`),{success:!0,skipped:!0}}return await At.rm(r,{recursive:!0,force:!0}),console.log(`Skill ${n} removed from ${r}.`),{success:!0}}catch(t){return Of(n,t,"Removal failed")}}async function Mf(n,e,t,r=!1){return dr(n,()=>Xc(e),i=>Qc(t,i,n),r)}async function _f(n,e,t,r=!1){return dr(n,()=>t,i=>Qc(e,i,n),r)}async function Ff(n,e,t,r,i=!1){return dr(n,()=>Zc(t,r),o=>Qc(e,o,n),i)}async function jf(n,e,t,r=!1){return dr(n,()=>Xc(t),i=>el(e,i,n),r)}async function Hf(n,e,t,r,i=!1){return dr(n,()=>Zc(t,r),o=>el(e,o,n),i)}async function $f(n,e,t,r=!1){return dr(n,()=>t,i=>el(e,i,n),r)}async function Uf(n,e){return tl(n,()=>Xc(e))}async function Bf(n,e){return tl(n,()=>e)}async function Wf(n,e,t){return tl(n,()=>Zc(e,t))}function Gf(){let e=J.dirname(Sb(import.meta.url));for(;;){let t=J.join(e,"SKILL.md");if(xf.existsSync(t))return t;let r=J.dirname(e);if(r===e)break;e=r}throw new Error("SKILL.md not found in deveco-cli package. Reinstall deveco-cli.")}import Vf from"fs";import{cyan as Db}from"colorette";async function gi(n){if(!n)return[];let e=[],t=n.split(",").map(r=>r.trim());for(let r of t){if(!await Kc(r))throw new Error(`Agent ${r} not found`);e.push(r)}return e}async function yi(){let n=[];for(let e of Object.keys(Ke))await Kc(e)&&n.push(e);return n}function wi(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(Db("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`),r>0&&(process.exitCode=1)}function Jt(n,e,t){if(!Vf.existsSync(n)){if(t)return;throw new Error(`${e} "${n}" not found`)}if(!Vf.statSync(n).isDirectory())throw new Error(`"${n}" is not a directory`)}function vi(n,e,t){if(n&&(e||t))throw new Error("Cannot use `--path` with `--project` or `--agent`");return{resolvedPath:n?Jc(n):void 0,resolvedProject:e?Jc(e):void 0}}async function ps(n,e,t){let r=[],i=[],o;if(e?o=e:t&&n.agent?i=(await gi(n.agent)).map(a=>({project:t,agent:a})):t?i=(await yi()).map(a=>({project:t,agent:a})):n.agent?r=await gi(n.agent):r=await yi(),!o&&r.length===0&&i.length===0)throw new Error("No agents found. Install an AI agent (cursor, opencode, etc.) or use `--path` for a custom location.");return{agents:r,projectAgents:i,customPath:o}}async function xb(n){let e=await ds();if(n.all)return(await zc(e)).map(r=>r.enName);{let r=(await qc(n.skill,e)).find(i=>i.enName===n.skill);if(!r)throw new Error(`Skill "${n.skill}" not found`);return[r.enName]}}async function Nb(n,e,t,r){let i=[];if(t.customPath){let o=await _f(n,e,t.customPath,r);return i.push(o),i}for(let o of t.agents){let s=await Mf(n,o,e,r);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await Ff(n,e,o,s,r);i.push(a)}return i}function Lb(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}=vi(n.path,n.project,n.agent);return t&&Jt(t,"Project directory",n.force),e&&Jt(e,"Directory",n.force),{resolvedPath:e,resolvedProject:t}}async function Ob(n,e,t){let r=await ps(n,e,t);return{skillNames:await xb(n),targets:r}}async function Mb(n,e,t,r){let i=[],o=n.length,s=Tb(5),a=n.map(c=>s(()=>_b(c)));for(let c=0;c<n.length;c++){let l=n[c],d=o>1?` (${c+1}/${o})`:"";r.start(`Installing ${l}${d}...`);let g=await a[c];if(!g.success){r.fail(),console.log(Si(`${l}: Download failed - ${g.error}`)),i.push({success:!1});continue}r.stop();let w=await Nb(l,g.buffer,e,t);i.push(...w)}return i}async function _b(n){try{let e=await Lf(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 Fb(n){let e=new tt;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:r}=Lb(n),{skillNames:i,targets:o}=await Ob(n,t,r),s=await Mb(i,o,n.force||!1,e);e.stop(),wi(s)}catch(t){throw e.stop(),t}}function jb(n){let{resolvedPath:e,resolvedProject:t}=vi(n.path,n.project,n.agent);return t&&Jt(t,"Project directory"),e&&Jt(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Hb(n,e){let t=new tt;try{t.start("Removing skill...");let{resolvedPath:r,resolvedProject:i}=jb(e);t.stop();let o=await $b(e,n,r,i);t.stop(),wi(o)}catch(r){throw t.stop(),r}}function zf(n,e=""){if(n.length===0)throw new Error(`No agents found. Install an AI agent (cursor, opencode, etc.) ${e}`)}async function fs(n,e){let t=[];for(let r of e){let i=r.type==="agent"?await Uf(n,r.agent):await Wf(n,r.project,r.agent);t.push(i)}return t}async function $b(n,e,t,r){if(t)return[await Bf(e,t)];if(r&&n.agent){let a=(await gi(n.agent)).map(c=>({type:"projectAgent",agent:c,project:r}));return fs(e,a)}if(r){let s=await yi();zf(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:r}));return fs(e,a)}if(n.agent){let a=(await gi(n.agent)).map(c=>({type:"agent",agent:c}));return fs(e,a)}let i=await yi();zf(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return fs(e,o)}var Ei=new Rb("skills").description("Manage HarmonyOS skills");Ei.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 ds(),r=await zc(t);if(r.length===0){e.stop(),console.log(Yf("No skills available."));return}e.succeed(`Fetched ${r.length} skills`);for(let i of r)if(n.long){console.log(qf(i.enName)),console.log(Jf(i.description));let o=Rf(i.enName);o.length>0&&console.log(kb(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(Si(t.message)),process.exit(1)}});Ei.command("find <keyword>").description("Search skills by keyword").action(async n=>{let e=new tt;try{e.start("Searching skills...");let t=await ds(),r=await qc(n,t);if(r.length===0){console.log(Yf(`No skills found matching '${n}'.`)),e.stop();return}e.succeed(`Found ${r.length} skills.`);for(let i of r)console.log(qf(i.enName)),console.log(Jf(i.description)),console.log()}catch(t){e.stop(),console.error(Si(t.message)),process.exit(1)}});Ei.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 Fb(n)}catch(e){console.error(Si(e.message)),process.exit(1)}});Ei.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 Hb(n.skill,n)}catch(e){console.error(Si(e.message)),process.exit(1)}});var Kf=Ei;import{Command as Bb,InvalidArgumentError as hs}from"commander";import{cyan as ms}from"colorette";function xn(n,e){if(n.exitCode===0)return null;let t=n.stderr||n.stdout,r=Yn(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 nl=[800,1500,2500];function Ub(n){return new Promise(e=>setTimeout(e,n))}var ur=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=Z.from(e)}createFollowLineHandler(){return(e,t)=>{if(t==="stderr"){for(let r of e)console.error(r);return}for(let r of e)console.log(r)}}findDeviceByArg(e,t){return e.find(r=>r.serial===t||r.name===t)}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1264
1264
|
`)}async loadConnectedDevicesByName(){return this.getConnectedDevices()}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!e&&t.length===1){let i=t[0];return m(ms(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return m(ms(`Using device serial: ${e}`)),e;let r=await this.loadConnectedDevicesByName();if(e){let i=this.findDeviceByArg(r,e);if(i)return m(ms(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(r);throw new Error(`Device '${e}' not found.
|
|
1265
1265
|
Available devices:
|
|
1266
|
-
${o}`)}if(r.length===1){let i=r[0];return m(ms(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),
|
|
1266
|
+
${o}`)}if(r.length===1){let i=r[0];return m(ms(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(r))}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,r){m(`Retrieving PID for bundle ${r}`),v.assertBundleNameStrict(r);let i=await X(e,["-t",t,"shell","pidof",r]),o=xn(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return m(`Found PID for ${r}: ${a}`),a}return m(`No PID found for bundle: ${r}`),null}async resizeHilogBuffer(e,t,r){m(`Setting hilog buffer size to: ${r}`);let i=await X(e,["-t",t,"shell","hilog","-G",r]),o=xn(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,r,i){let o=this.buildHilogShellCommand(r,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let r=["hilog"];return e.isFollow||r.push("-x"),e.tag&&(v.assertHilogToken(e.tag,"tag"),r.push("-T",e.tag)),e.level&&(v.assertHilogLevel(e.level),r.push("-L",e.level)),e.domain&&(v.assertHilogToken(e.domain,"domain"),r.push("-D",e.domain)),t&&r.push("-P",t),e.keyword&&(v.assertHilogKeyword(e.keyword),r.push("-e",v.quotePosixShellArg(e.keyword))),r.join(" ")}async followHilog(e,t,r,i,o){let a=await Lu(e,t,{onData:r,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,r,i,o){let s=1+nl.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){if(a=await this.followHilog(e,t,r,i,o),a.exitCode===0||Yn(a.stderr)!=="transient"||c>=s-1)return a;m(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${nl[c]}ms`),await Ub(nl[c])}return a}async runHilogStreamingCollect(e,t,r){return this.runHilogWithSpawnRetry(e,t,()=>{},i=>{m(`Callback triggered when an error occurs during ${r}: ${i.message}`)},()=>{})}async printTailSnapshotIfNeeded(e,t,r,i){if(!r.tail&&!r.fromSeconds&&!r.toSeconds)return;let o={...r,isFollow:!1},[s,a]=this.buildHilogCommand(e,t,o,i);m(`Ready to run hilog snapshot command: ${s} ${a.join(" ")}`);let c=await this.runHilogStreamingCollect(s,a,"a hilog snapshot streaming read"),l=xn(c,"Failed to get hilog");if(l)throw l;if(c.exitCode!==0&&c.stderr)throw new Error(`Failed to get hilog: ${c.stderr}`);let d=v.filterLogsByRelativeWindow(c.stdout||c.stderr,r.fromSeconds,r.toSeconds);d=v.getLastLines(d,r.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,r,i){let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogStreamingCollect(o,s,"a single hilog streaming read"),c=xn(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let l=a.stdout||a.stderr,d=v.filterLogsByRelativeWindow(l,r.fromSeconds,r.toSeconds);return d=v.getLastLines(d,r.tail),d}async runHilogFollow(e,t,r,i){try{await this.printTailSnapshotIfNeeded(e,t,r,i)}catch(l){console.error(`Warning: Failed to fetch log snapshot, continuing with live stream: ${l.message}`)}let[o,s]=this.buildHilogCommand(e,t,r,i);m(`Ready to run hilog command which contain \`follow\` and \`tail\`: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(),l=>{m(`Spawn error during hilog follow: ${l.message}`)},()=>{}),c=xn(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let r=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(r,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Ensure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(r,e,t.logSize),t.isFollow?await this.runHilogFollow(r,e,t,i||""):await this.getHilogOnce(r,e,t,i||"")}async getCrashLog(e,t){m(`Fetching crash logs from device: ${e}`);let r=this.toolProvider.hdcPath,i=await this.listCrashLogs(r,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,l)=>{let d=c.split("-").pop()||"";return(l.split("-").pop()||"").localeCompare(d)})[0],a=await this.fetchCrashLogContent(r,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,r){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];m(`Running command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log list streaming read"),s=xn(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return m(`Crash logs list output:
|
|
1267
1267
|
${o.stdout}`),this.parseCrashLogFilenames(o.stdout,r)}parseCrashLogFilenames(e,t){return e.split(`
|
|
1268
|
-
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return E.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=xn(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as tl,red as Yf}from"colorette";import Nb from"ora";function Ob(n){try{return E.parsePositiveInteger(n,"tail")}catch{throw new nl("`tail` must be a positive integer.")}}function qf(n,e){try{return E.parseDurationToSeconds(n,e)}catch{throw new nl(`${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 Mb(n){try{return E.assertHilogLevel(n),n}catch{throw new nl("`level` must be one of: D, I, W, E, F.")}}function _b(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function Fb(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function jb(n,e,t,r){let i=E.filterLogsByRelativeWindow(n,t,r);return e.tail?E.getLastLines(i,e.tail):i}var Hb=new Lb("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Yf(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",Mb).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",Ob).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>qf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>qf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await $b(n)});async function $b(n){let e=Nb({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),_b(n);let r=n.from,i=n.to,o=await I.new(),s=new ur(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(tl(`deviceId: ${a}`)),m(tl(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(tl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Fb(s,a,n,r,i);t(),n.crash&&c&&(c=jb(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(Yf(r.message)),process.exit(1)}}var Jf=Hb;import Pi from"path";import Rt from"fs";import il from"process";import im from"os";import{Command as Qb}from"commander";import{green as em,red as rl,cyan as eP,yellow as tm}from"colorette";import oe from"fs-extra";import _ from"path";import*as Xf from"os";import{fileURLToPath as Ub}from"url";var Kf={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"}},Bb=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function Wb(){let n=import.meta.url,e=Ub(n);if(e.includes("dist")){let o=_.dirname(e),s=_.dirname(o);return _.join(s,"templates","application")}let t=_.dirname(e),r=_.dirname(t),i=_.dirname(r);return _.join(i,"templates","application")}function Zf(n,e){oe.mkdirSync(e,{recursive:!0});for(let t of oe.readdirSync(n,{withFileTypes:!0})){let r=_.join(n,t.name),i=_.join(e,t.name);if(t.isDirectory()){Zf(r,i);continue}oe.existsSync(i)||(oe.mkdirSync(_.dirname(i),{recursive:!0}),oe.copyFileSync(r,i))}}function bi(n,e){let t=oe.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&oe.writeFileSync(n,r,"utf-8")}function Gb(n){if(Kf[n])return Kf[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function Vb(n,e){if(e===22)return;let t=Gb(e);t&&(bi(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),bi(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),bi(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function zb(n){return Bb.filter(t=>!oe.existsSync(_.join(n,t))).length===0}function qb(){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 Yb(n){return Xf.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function Jb(n,e){let t=Yb(e);if(!oe.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=_.join(t,i),a=_.join(n,o);oe.existsSync(s)&&(oe.mkdirSync(_.dirname(a),{recursive:!0}),oe.copyFileSync(s,a))}return!0}function Kb(n){let e=qb(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=_.join(n,r);oe.mkdirSync(_.dirname(i),{recursive:!0}),oe.writeFileSync(i,e)}}function Xb(n,e){e&&Jb(n,e)||Kb(n)}function Zb(n){let e=[_.join(n,"gitignore.txt"),_.join(n,"entry","gitignore.txt")];for(let t of e)if(oe.existsSync(t)){let r=_.dirname(t);oe.renameSync(t,_.join(r,".gitignore"))}}function Qf(n,e,t,r,i){let o=Wb();if(!oe.existsSync(o))throw new Error(`Template directory not found: ${o}`);oe.mkdirSync(n,{recursive:!0}),Zf(o,n),Zb(n),Xb(n,i),bi(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),bi(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),Vb(n,r);let s=zb(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function tP(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 nP(n){if(n.length<7||n.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${n.length}`);if(n.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example").');let e=n.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 dot-separated segments.");let t=/^[a-zA-Z0-9_]+$/;for(let r=0;r<e.length;r++){let i=e[r];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(r===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z).`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit.`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit.`)}}function om(n){if(im.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function nm(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=im.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=om(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 rP(n){let e=n,t=Pi.parse(n).root;for(;e!==t;){if(Rt.existsSync(e))return e;e=Pi.dirname(e)}return Rt.existsSync(t)?t:null}function rm(n){let e=rP(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Rt.accessSync(e,Rt.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Pi.join(e,`.deveco_write_test_${Date.now()}`);try{Rt.writeFileSync(t,"test"),Rt.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function iP(n){return`com.example.${n.toLowerCase()}`}function oP(n,e){if(e){let i=om(e),o=Pi.resolve(i);if(Rt.existsSync(o)){if(Rt.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else rm(o);return o}let t=il.cwd(),r=Pi.join(t,n);if(Rt.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return rm(r),r}function sP(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function aP(){try{return await I.new()}catch(n){console.error(tm(`DevEco Studio not found: ${n.message}`)),console.log(tm("Use placeholder API level instead."));return}}var cP=new Qb("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(rl("Error: --app-name is required")),il.exit(1));let e=n.appName;tP(e);let t=n.bundleName||iP(e);nP(t),n.projectPath&&nm(n.projectPath);let r=oP(e,n.projectPath);nm(r),console.log(eP("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await aP(),o=sP(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Qf(r,e,t,o,s);console.log(`
|
|
1269
|
-
`+
|
|
1270
|
-
Failed to create project.`)),console.error(
|
|
1268
|
+
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>{try{return v.assertCrashFilename(r),!0}catch{return!1}}).filter(r=>t?r.toLowerCase().includes(t.toLowerCase()):!0)}async fetchCrashLogContent(e,t,r){m(`Fetching latest crash log file: ${r}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${r}`];m(`Executing command: ${e} ${i.join(" ")}`);let o=await this.runHilogStreamingCollect(e,i,"a crash log streaming read"),s=xn(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash logs: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as rl,red as Zf}from"colorette";import Wb from"ora";function Gb(n){try{return v.parsePositiveInteger(n,"tail")}catch{throw new hs("`tail` must be a positive integer.")}}function Xf(n,e){try{return v.parseDurationToSeconds(n,e)}catch{throw new hs(`${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 Vb(n){try{return v.assertHilogLevel(n),n}catch{throw new hs("`level` must be one of: D, I, W, E, F.")}}function zb(n){try{return v.assertBundleNameStrict(n),n}catch(e){throw new hs(e.message)}}function qb(n){if(n.to&&n.follow)throw new Error("`--to` cannot be used with `--follow`.")}async function Yb(n,e,t,r,i){return t.crash?await n.getCrashLog(e,t.bundleName):await n.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:r,toSeconds:i})}function Jb(n,e,t,r){let i=v.filterLogsByRelativeWindow(n,t,r);return e.tail?v.getLastLines(i,e.tail):i}var Kb=new Bb("log").description("Obtain device application logs").configureOutput({outputError:(n,e)=>e(Zf(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",Vb).option("--bundle-name <bundle-name>","Filter by application bundle name",zb).option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",Gb).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Xf(n,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",n=>Xf(n,"to")).option("--follow","Follow the log stream in real-time.").action(async n=>{await Xb(n)});async function Xb(n){let e=Wb({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),qb(n);let r=n.from,i=n.to,o=await A.new(),s=new ur(o),a=await s.selectDevice(n.device);a||(t(),process.exit(1)),m(rl(`deviceId: ${a}`)),m(rl(`type: ${n.crash?"Crash logs":"Common logs"}`)),m(rl("Obtaining logs ...")),e.text="Fetching logs\u2026",n.follow&&t();let c=await Yb(s,a,n,r,i);t(),n.crash&&c&&(c=Jb(c,n,r,i)),c&&console.log(c)}catch(r){t(),console.error(Zf(r.message)),process.exit(1)}}var Qf=Kb;import Pi from"path";import Dt from"fs";import ol from"process";import cm from"os";import{Command as dP}from"commander";import{green as im,red as il,cyan as uP,yellow as om}from"colorette";import ie from"fs-extra";import _ from"path";import*as tm from"os";import{fileURLToPath as Zb}from"url";var em={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"}},Qb=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function eP(){let n=import.meta.url,e=Zb(n);if(e.includes("dist")){let o=_.dirname(e),s=_.dirname(o);return _.join(s,"templates","application")}let t=_.dirname(e),r=_.dirname(t),i=_.dirname(r);return _.join(i,"templates","application")}function nm(n,e){ie.mkdirSync(e,{recursive:!0});for(let t of ie.readdirSync(n,{withFileTypes:!0})){let r=_.join(n,t.name),i=_.join(e,t.name);if(t.isDirectory()){nm(r,i);continue}ie.existsSync(i)||(ie.mkdirSync(_.dirname(i),{recursive:!0}),ie.copyFileSync(r,i))}}function bi(n,e){let t=ie.readFileSync(n,"utf-8"),r=t;for(let[i,o]of e)r=r.replaceAll(i,o);r!==t&&ie.writeFileSync(n,r,"utf-8")}function tP(n){if(em[n])return em[n];if(n>=26){let e=`${n}.0.0`;return{sdkVersion:e,modelVersion:e}}}function nP(n,e){if(e===22)return;let t=tP(e);t&&(bi(_.join(n,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),bi(_.join(n,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),bi(_.join(n,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function rP(n){return Qb.filter(t=>!ie.existsSync(_.join(n,t))).length===0}function iP(){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 oP(n){return tm.platform()==="darwin"?_.join(n,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):_.join(n,"plugins","codegenie-plugin","previewProjectTemplate")}function sP(n,e){let t=oP(e);if(!ie.existsSync(t))return!1;let r=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of r){let s=_.join(t,i),a=_.join(n,o);ie.existsSync(s)&&(ie.mkdirSync(_.dirname(a),{recursive:!0}),ie.copyFileSync(s,a))}return!0}function aP(n){let e=iP(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let r of t){let i=_.join(n,r);ie.mkdirSync(_.dirname(i),{recursive:!0}),ie.writeFileSync(i,e)}}function cP(n,e){e&&sP(n,e)||aP(n)}function lP(n){let e=[_.join(n,"gitignore.txt"),_.join(n,"entry","gitignore.txt")];for(let t of e)if(ie.existsSync(t)){let r=_.dirname(t);ie.renameSync(t,_.join(r,".gitignore"))}}function rm(n,e,t,r,i){let o=eP();if(!ie.existsSync(o))throw new Error(`Template directory not found: ${o}`);ie.mkdirSync(n,{recursive:!0}),nm(o,n),lP(n),cP(n,i),bi(_.join(n,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),bi(_.join(n,"AppScope","app.json5"),[["com.example.myapplication",t]]),nP(n,r);let s=rP(n);if(!s)throw new Error("Template integrity check failed.");return{projectRoot:n,appName:e,bundleName:t,apiLevel:r,verified:s}}function pP(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 lm(n){if(cm.platform()==="win32"){let t=n.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return n.replace(/\/+/g,"/")}function sm(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=cm.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(n)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}.`)}let r=lm(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 fP(n){let e=n,t=Pi.parse(n).root;for(;e!==t;){if(Dt.existsSync(e))return e;e=Pi.dirname(e)}return Dt.existsSync(t)?t:null}function am(n){let e=fP(n);if(!e)throw new Error(`No existing parent directory found for '${n}'. Cannot create project directory.`);try{Dt.accessSync(e,Dt.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Pi.join(e,`.deveco_write_test_${Date.now()}`);try{Dt.writeFileSync(t,"test"),Dt.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function mP(n){return`com.example.${n.toLowerCase()}`}function hP(n,e){if(e){let i=lm(e),o=Pi.resolve(i);if(Dt.existsSync(o)){if(Dt.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project here.`)}else am(o);return o}let t=ol.cwd(),r=Pi.join(t,n);if(Dt.existsSync(r))throw new Error(`Directory '${r}' already exists. Cannot create project here.`);return am(r),r}function gP(n,e){let t=e?.getMaxApiLevel(),r=23;if(n.apiLevel){let i=Number(n.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API version ${n.apiLevel}. API version 17 or higher is required.`);if(t!==void 0){if(i>t)throw new Error(`Invalid API version ${n.apiLevel}. Your SDK supports API version 17-${t}`)}else if(i>r)throw new Error(`Invalid API version ${n.apiLevel}. Without DevEco Studio, supported range is API version 17-${r}`);return i}return t!==void 0?t:23}async function yP(){try{return await A.new()}catch(n){console.error(om(`DevEco Studio not found: ${n.message}`)),console.log(om("Use placeholder API level instead."));return}}var wP=new dP("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(il("Error: --app-name is required")),ol.exit(1));let e=n.appName;pP(e);let t=n.bundleName||mP(e);v.assertBundleNameStrict(t),n.projectPath&&sm(n.projectPath);let r=hP(e,n.projectPath);sm(r),console.log(uP("Initializing project...")),console.log(`Project path: ${r}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await yP(),o=gP(n,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=rm(r,e,t,o,s);console.log(`
|
|
1269
|
+
`+im("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(im("Template integrity check passed."))}catch(e){let t=e;console.error(il(`
|
|
1270
|
+
Failed to create project.`)),console.error(il(t.message)),ol.exit(1)}}),dm=wP;import{Command as IP}from"commander";import{red as AP,cyan as ym}from"colorette";import vP from"fs";import gs from"path";import{cyan as SP}from"colorette";import*as ys from"smol-toml";var pr=vP.promises;async function EP(n){try{let e=await pr.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 bP(n){try{let e=await pr.readFile(n,"utf8");return e.trim()===""?{}:ys.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 PP(n,e){let t=gs.dirname(n);await pr.mkdir(t,{recursive:!0});let r=JSON.stringify(e,null,2);await pr.writeFile(n,r,"utf8")}async function CP(n,e){let t=gs.dirname(n);await pr.mkdir(t,{recursive:!0});let r=ys.stringify(e);await pr.writeFile(n,r,"utf8")}function um(n,e,t){let r=n[e];return!r||typeof r!="object"?!1:t in r}function pm(n,e,t,r,i){(!n[e]||typeof n[e]!="object")&&(n[e]={});let o=n[e];return t in o&&!i?!1:(o[t]=r,!0)}async function fm(n,e){return n.format==="codex"?bP(e):EP(e)}async function mm(n,e,t){return n.format==="codex"?CP(e,t):PP(e,t)}async function hm(n,e,t=!1){let r=Ft[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ft).join(", ")}`};if(!r.supportsGlobal)return{success:!1,error:`${r.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await fm(r,r.globalConfigPath);if(um(i,r.mcpServersKey,lt)&&!t)return console.log(`MCP server ${lt} already configured in ${r.globalConfigPath}.`),{success:!0,skipped:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"};let o=mo(r,void 0);return pm(i,r.mcpServersKey,lt,o,t),await mm(r,r.globalConfigPath,i),console.log(`MCP server ${lt} configured in ${r.globalConfigPath}.`),{success:!0,configPath:r.globalConfigPath,agentName:n,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${i.message}`}}}async function sl(n,e,t=!1){let r=Ft[n];if(!r)return{success:!1,error:`Unknown agent: ${n}. Supported agents: ${Object.keys(Ft).join(", ")}`};let i=gs.isAbsolute(r.projectConfigPath)?r.projectConfigPath:gs.join(e,r.projectConfigPath);try{let o=await fm(r,i);if(um(o,r.mcpServersKey,lt)&&!t)return console.log(`MCP server ${lt} already configured in ${i}.`),{success:!0,skipped:!0,configPath:i,agentName:n,installType:"project"};let s=mo(r,e);return pm(o,r.mcpServersKey,lt,s,t),await mm(r,i,o),console.log(`MCP server ${lt} configured in ${i}.`),{success:!0,configPath:i,agentName:n,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${r.displayName}: ${o.message}`}}}function gm(n){let e=n.filter(i=>i.success&&!i.skipped).length,t=n.filter(i=>i.skipped).length,r=n.filter(i=>!i.success).length;console.log(),console.log(SP("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${r}`);for(let i of n)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);r>0&&(process.exitCode=1)}var al="deveco-cli";async function DP(n,e,t){if(n.customPath)return[await $f(al,e,n.customPath,t.force)];let r=[...n.projectAgents.map(({project:s,agent:a})=>()=>Hf(al,e,s,a,t.force)),...n.agents.map(s=>()=>jf(al,e,s,t.force))],i=5,o=[];for(let s=0;s<r.length;s+=i){let a=r.slice(s,s+i);o.push(...await Promise.all(a.map(c=>c())))}return o}async function RP(n,e,t){let r=[];for(let{project:i,agent:o}of n.projectAgents){let s=await sl(o,i,t);r.push(s)}for(let i of n.agents){let o=await sl(i,e,t);r.push(o)}return r}async function kP(n,e){let t=[];for(let r of n){if(!Ft[r])continue;let o=await hm(r,process.cwd(),e);t.push(o)}return t}async function TP(n,e,t){if(t.agent&&t.agent.split(",").map(l=>l.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other supported agents instead.");let r=t.force??!1,i=n.projectAgents.filter(c=>c.agent!=="qoder"),o=n.agents.filter(c=>c!=="qoder"),s={...n,projectAgents:i,agents:o},a=e?await RP(s,e,r):await kP(s.agents,r);a.length>0&&(console.log(ym("MCP Configuration:")),gm(a))}async function xP(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}=vi(n.path,n.project,n.agent);t&&Jt(t,"Project directory",n.force),e&&Jt(e,"Directory",n.force);let r=await ps(n,e,t);if(n.mcp){await TP(r,t,n);return}let i=Gf(),o=await DP(r,i,n);console.log(),o.length>0&&(console.log(ym("Skill Installation:")),wi(o))}var NP=new IP("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 xP(n)}catch(e){console.error(AP(e instanceof Error?e.message:String(e))),process.exit(1)}}),wm=NP;import{Command as AC}from"commander";import{McpServer as dC}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as uC}from"@modelcontextprotocol/sdk/server/stdio.js";import*as Xs from"path";import{z as oe}from"zod";var ws=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:r}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>r(i)))}};function cl(){return new ws}import*as Ne from"fs";import*as he from"path";import{z as pl}from"zod";function vm(n){return"method"in n&&!("id"in n)}import{spawn as LP}from"child_process";import{EventEmitter as OP}from"events";import*as fr from"fs";import*as Sm from"path";var Kt=class extends OP{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;ensureDirectories(){let t=Sm.join(this.config.logPath,"lspLog");return fr.existsSync(t)||fr.mkdirSync(t,{recursive:!0}),fr.existsSync(this.config.indexingDataLocation)||fr.mkdirSync(this.config.indexingDataLocation,{recursive:!0}),t}async start(t){let r=this.ensureDirectories();f.info(`[LspClient] serverMaxSize=${t}MB`);let i=U(r),o=["--expose-gc",`--max-old-space-size=${t}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];f.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";f.info(`[LspClient] nodePath: ${s}`),this.process=LP(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.bindProcessEvents(),await new Promise(a=>setTimeout(a,500)),f.info("[LspClient] start lsp process success")}attachProcess(t,r){if(this.process)throw new Error("[LspClient] process already attached");this.process=t,this.bindProcessEvents(r?.stderrAsError??!0),f.info("[LspClient] attached to external process")}bindProcessEvents(t=!0){this.process&&(this.process.stdout?.on("data",r=>{this.handleData(r)}),this.process.stderr?.on("data",r=>{let i=r.toString("utf8").trim();f.error(`[LspClient] stderr: ${i}`),!this.isClosing&&t&&this.emit("error",new Error(`[LspClient] stderr: ${i}`))}),this.process.on("exit",r=>{f.info(`[LSP EXIT] code=${r}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${r}`))}))}sendRaw(t,r){if(!this.process?.stdin?.writable){f.warn("[LspClient] Cannot send message, stdin not writable");return}f.info(`[LspClient] send message: ${r}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,r,i){let o={jsonrpc:"2.0",method:t,params:r};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}sendNotification(t,r){this.sendRaw(JSON.stringify({jsonrpc:"2.0",method:t,params:r}),t)}sendRequest(t,r,i){this.sendRaw(JSON.stringify({jsonrpc:"2.0",id:i,method:t,params:r}),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1271
1271
|
\r
|
|
1272
1272
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1273
1273
|
\r
|
|
1274
|
-
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Xt=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,r)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var ws=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var mr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function D(n){return typeof n=="object"&&n!==null}var ym=20*1e3,IP=30*1e3,vs=class{client;nextRequestId=1;stopOnce=null;callbacks=new mr;requestCallbacks=new Xt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Kt(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,_e);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new ws(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=IP){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){D(e)&&this.broadcastToClients({jsonrpc:R,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,ym,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${ym}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:R,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Ss=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new cl(e,t))}clearMessages(){this.messages=[]}clear(){this.receivedTypes.clear(),this.uniqueMessages.clear(),this.messages=[]}hasReceivedAllTypes(e){for(let t of e)if(!this.receivedTypes.has(t))return!1;return!0}getMessages(){return this.messages.map(e=>e.diagnostics)}},cl=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var AP={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"},DP={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},k={...AP,...DP},Zt={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"},wm=new Set([1e3,2e3,3e3,3001]);function RP(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function kP(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function TP(n){return D(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var Es=class n{client;isInitialized=!1;stopOnce=null;callbacks=new mr;requestCallbacks=new Xt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Kt(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.EXIT,params:{}}),Zt.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(k.BROADCAST),this.callbacks.register(k.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(k.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(k.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(k.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.INITIALIZED,params:{editors:e}}),Zt.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:R,id:0,result:{}}),Zt.EMPTY)}sendAsyncRequest(e,t,r,i){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!RP(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=Qe(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!kP(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),k.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Zt.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Qe(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Ss(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,k.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Zt.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Qe(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,k.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Zt.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Qe(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:R,method:k.DID_CLOSE,params:{textDocument:{uri:r}}}),Zt.DID_CLOSE)}getDiagnosticMessage(e){let t=Qe(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,k.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:R,method:k.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 k.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(k.MODULE_INIT_FINISH),this.callbacks.unregister(k.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case k.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${TP(t.params)}`),this.callbacks.invoke(k.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case k.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case k.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case k.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case k.ON_ASYNC_HOVER:this.handleAsyncResponse(t,k.HOVER);return;case k.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,k.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case k.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,k.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;D(t)&&D(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:R,method:k.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!D(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,k.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(wm)&&this.finalizeDiagnostic(t,k.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import ll from"path";import*as Rs from"path";var bs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Ps=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Cs=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Is=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var As=class{typeSetting=new Cs;parameterNames=new Is};var Ds=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=U(Rs.dirname(t)),this.indexingDataLocation=U(i),this.loggerPath=U(Rs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new bs;gutterIconsSetting=new Ps;inlayHintsSetting=new As;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as vm from"path";var Ci=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(U(vm.join(e,"src","main","resources")))}};var xP="OS",hr=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${xP}`;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 Ci(e)):this.buildProfileParam=new Ci}toString(){return JSON.stringify(this)}};var gr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Ge from"path";import*as vr from"fs";var ks=class{modulePath;dependencies={};dynamicDependencies={}};var Ln=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 yr=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 kt from"path";import*as Ts from"fs";var wr=class{name="";version="";storePath="";dependencyPath="";path=""};var N={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Ze.OH_PACKAGE_JSON5},Ii=`${N.HVIGOR_CACHE}/${N.DEPENDENCY}`,Nn=`${N.DEPENDENCY}${N.JSON5}`,tU=Ze.SYNC_OUTPUT_PATH;var Ai=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=kt.join(this.dependencyPath,N.OH_PACKAGE_JSON5),r=Te(t);r&&(this.dependencies=this.getDependencyList(r,N.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,N.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,N.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!D(e))return r;let i=e[t];if(!D(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new wr;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=kt.normalize(kt.join(this.modulePath,N.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),kt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=kt.resolve(this.modulePath,s);o=E.ensurePathWithinRoot(this.projectPath,a)}Ts.existsSync(o)&&Ts.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as On from"fs";import*as Di from"path";import LP from"json5";var xs=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;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 Di.join(this.projectPath,N.OH_MODULES_PATH,N.OHPM_PATH,N.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!n.checkObjectDepth(i,t,r+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!n.checkObjectDepth(e[i],t,r+1))return!1;return!0}readLockFile(e){if(!On.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=On.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return f.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return f.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=On.readFileSync(e,"utf8"),r=LP.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(f.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!D(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,N.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,N.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,N.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!D(o)){f.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(D(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!D(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!D(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!D(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",w=new wr;w.name=c,w.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(w,r,c,d,g);let P=`${c}@${g}`;this.storePathMap.has(P)&&(w.storePath=this.storePathMap.get(P)||""),o.push(w)}return o}parseDependencyPath(e,t,r,i,o){let s=E.resolvePathWithinRoot(this.projectPath,Di.join(t,N.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=Di.isAbsolute(a)?E.ensurePathWithinRoot(this.projectPath,a):E.resolvePathWithinRoot(this.projectPath,a);On.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Sm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Mn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new Et(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Ge.join(t,Ii),i=Ge.join(r,Nn);if(!vr.existsSync(r)||!vr.existsSync(i)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new yr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];Sm(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=Ge.join(r,Ii),o=Ge.join(i,Nn);if(!vr.existsSync(i)||!vr.existsSync(o))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new yr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Sm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let g=E.resolvePathWithinRoot(this.projectPath,l.srcPath),w=Ge.join(i,d),P=U(g),O=this.buildModuleDependencies(d,P,w,a);O.moduleName=d,t.push(O)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=E.resolvePathWithinRoot(this.projectPath,e.srcPath),a=Ge.join(t,o),c=U(s),l=new hr(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new gr(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new yr(this.projectPath,e,t);Ai.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new ks;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new Ln(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Ln(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Ge.join(e,N.OH_PACKAGE_JSON5);if(!vr.existsSync(r))return;Ai.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 xs(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ge.join(e,"src","main","module.json5"),i=Te(r);if(!D(i)||!D(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(D(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)D(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Ge.join(e,"src","main","resources","base","profile","main_pages.json"),r=Te(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!D(t)||!D(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=Ge.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Te(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!D(t)||!D(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!D(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Ge.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Te(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!D(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Ls=class{constructor(e=[]){this.valueSet=e}valueSet};var Sr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Em=(b=>(b[b.File=1]="File",b[b.Module=2]="Module",b[b.Namespace=3]="Namespace",b[b.Package=4]="Package",b[b.Class=5]="Class",b[b.Method=6]="Method",b[b.Property=7]="Property",b[b.Field=8]="Field",b[b.Constructor=9]="Constructor",b[b.Enum=10]="Enum",b[b.Interface=11]="Interface",b[b.Function=12]="Function",b[b.Variable=13]="Variable",b[b.Constant=14]="Constant",b[b.String=15]="String",b[b.Number=16]="Number",b[b.Boolean=17]="Boolean",b[b.Array=18]="Array",b[b.Object=19]="Object",b[b.Key=20]="Key",b[b.Null=21]="Null",b[b.EnumMember=22]="EnumMember",b[b.Struct=23]="Struct",b[b.Event=24]="Event",b[b.Operator=25]="Operator",b[b.TypeParameter=26]="TypeParameter",b))(Em||{}),bm=()=>Object.values(Em).filter(n=>typeof n=="number");var Ns=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Os=class{applyEdit=!0;workspaceEdit=new Ns;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ls(bm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Sr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Ms=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var _s=class{constructor(e=[]){this.valueSet=e}valueSet};var Fs=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Pm=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(Pm||{}),Cm=()=>Object.values(Pm).filter(n=>typeof n=="number");var js=class{completionItemKind=new _s(Cm());completionItem=new Fs;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Hs=class{synchronization=new Ms;completion=new js;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 Sr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var $s=class{workspace=new Os;textDocument=new Hs;notebookDocument=null;window=null;general=null;experimental=null};var Us=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Bs=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=zr(t,this.useStandardProtocol),this.logPath=vu(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new vs(a):new Es(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=Qe(this.rootUri),o=new Ds(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Mn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=xo(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Us(i,o,new $s),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,_e),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:R,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",_e),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:R,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new Mn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new Ln({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new hr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new gr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=qn(ll.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=qn(ll.join(t,"default/openharmony/ets/api")),o=qn(ll.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:R,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:R,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!hm(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as Tt from"fs";import*as Qt from"path";import{createHash as OP}from"crypto";import{EventEmitter as MP}from"events";var Ws=class extends MP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Tt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Tt.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=E.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=E.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=E.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=E.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Te(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Qt.join(this.projectRoot,N.OH_PACKAGE_JSON5);Tt.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=E.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Qt.join(s,N.OH_PACKAGE_JSON5);Tt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Qt.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Tt.readFileSync(t,"utf-8");return OP("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=Tt.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Qt.basename(t),relativePath:Qt.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as en from"fs";import*as nt from"path";import{createHash as _P}from"crypto";import{EventEmitter as FP}from"events";var Gs=class extends FP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=nt.join(t,Ii)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!en.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=en.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return U(nt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===N.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Nn)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=nt.join(this.depMapDir,r);en.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=nt.join(this.depMapDir,N.OH_PACKAGE_JSON5),r=nt.join(this.depMapDir,Nn),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:nt.join(this.depMapDir,s.name,N.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!en.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=nt.join(this.depMapDir,Nn);try{let r=Te(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return U(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=nt.join(this.depMapDir,a.name,N.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=nt.join(this.depMapDir,o,N.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=en.readFileSync(t,"utf-8");return _P("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as jP}from"child_process";import*as dl from"fs";import*as Ri from"path";var HP=["install","--all"];function $P(n){let e=n.replace(/sdk\/?$/i,"tools"),t=Ri.join(e,"ohpm","bin","pm-cli.js");if(dl.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?Ri.dirname(n):n;return t=Ri.join(r,"ohpm","bin","pm-cli.js"),dl.existsSync(t)?t:null}async function UP(n,e,t,r){return new Promise(i=>{let o=jP(n,[e,...HP],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1274
|
+
`);if(r===-1)break;let o=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(o[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),d=this.recoverFramedJson(l);if(d&&d.rest.length>0){f.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${l.length}, restLen=${d.rest.length}`),this.emit("message",d.json),this.buffer=Buffer.concat([Buffer.from(d.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",l),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let r=this.process;return!r||r.exitCode!==null||r.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),r.off("exit",a),i())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let i=0,o=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let l=t.slice(r,a+1),d=t.slice(a+1);return{json:l,rest:d}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var Xt=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((i,o)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),o(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:i,reject:o,method:t,timer:s})})}resolvePending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.resolve(t),this.pending.delete(e),!0):!1}rejectPending(e,t){this.clearTimeout(e);let r=this.pending.get(e);return r?(r.reject(t),this.pending.delete(e),!0):!1}register(e,t){this.callbacks.set(e,t)}emit(e,t,r){f.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);if(i)try{i(t,r)}finally{this.callbacks.delete(e)}else{let o=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${o.join(",")}]`)}}registerTimeout(e,t,r,i){let o=this.timeouts.get(e);o&&clearTimeout(o);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`);try{i()}finally{this.timeouts.delete(e)}},r);this.timeouts.set(e,s)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)||this.pending.has(e)}clear(e){this.clearTimeout(e);let t=this.pending.get(e);t&&(t.reject(new Error(`Request '${t.method}' (id=${e}) cancelled`)),this.pending.delete(e)),this.callbacks.delete(e)}rejectAll(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear();for(let[,t]of this.timeouts)clearTimeout(t);this.timeouts.clear(),this.callbacks.clear()}};var vs=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var mr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let i of r)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function D(n){return typeof n=="object"&&n!==null}var Em=20*1e3,MP=30*1e3,Ss=class{client;nextRequestId=1;stopOnce=null;callbacks=new mr;requestCallbacks=new Xt;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new Kt(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[ClientMessageHandle] Sending shutdown request"),this.client.sendRequest(y.SHUTDOWN,null,this.nextRequestId++),f.info("[ClientMessageHandle] Sending exit notification"),this.client.sendNotification(y.EXIT,null),f.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(y.BROADCAST),this.callbacks.register(y.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(y.BROADCAST,e)}async sendInitialize(e){let t=this.nextRequestId++,r=this.requestCallbacks.registerPending(t,y.INITIALIZE,Fe);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,i=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((o,s)=>{let a,c=()=>{a=setTimeout(()=>{this.initProgressReset=null,s(new Error(`LSP initialization timeout after ${t}ms`))},t)},l=()=>{clearTimeout(a),c()};this.initProgressReset=l,c(),i.then(()=>{clearTimeout(a),this.initProgressReset=null,o()},d=>{clearTimeout(a),this.initProgressReset=null,s(d)})})}sendInitialized(){this.client.sendNotification(y.INITIALIZED,{})}sendDidOpen(e){let t=e.textDocument.uri;this.diagnosticMap.has(t)||(this.diagnosticMap.set(t,new vs(t)),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_OPEN,e)}sendDidChange(e){let t=e.textDocument.uri,r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t)),this.client.sendNotification(y.DID_CHANGE,e)}closeFile(e){this.cleanupDiagnosticState(e.textDocument.uri),this.client.sendNotification(y.DID_CLOSE,e)}sendLspRequest(e,t,r=MP){let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}onDidChangeWatchedFiles(e){e.length!==0&&this.client.sendNotification(y.WORKSPACE_DID_CHANGE_WATCHED_FILES,{changes:e})}sendDidChangeConfiguration(e){this.client.sendNotification(y.WORKSPACE_DID_CHANGE_CONFIGURATION,{settings:e})}sendNotification(e,t){this.client.sendNotification(e,t)}getDiagnosticMessages(e){let t=this.diagnosticMap.get(e);return t?t.get():[]}clearDiagnostic(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${i}, raw: ${e}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotificationOrRequest(t):f.warn(`[LSP] Unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t===void 0)return;let r=t;if(e.error){let i=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,i)}else this.requestCallbacks.resolvePending(r,e.result)}handleNotificationOrRequest(e){let t=e.method;if(t)switch(this.initProgressReset?.(),t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.handleProgress(e.params);break;case y.WINDOW_SHOW_MESSAGE:f.info(`[LSP] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[LSP] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.broadcastToClients(e)}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=e.uri,r=this.diagnosticMap.get(t);if(!r)return;let i=e.diagnostics||[];this.normalizeDiagnostics(i),r.set(i),this.finalizeDiagnostic(t,i)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){D(e)&&this.broadcastToClients({jsonrpc:k,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Em,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Em}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let i={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,i),this.diagnosticMap.get(e)?.clear()}handleError(e){let t=Array.from(this.diagnosticMap.keys()).filter(r=>this.requestCallbacks.hasCallback(r));if(t.length>0){let r={range:{start:{line:0,character:0},end:{line:0,character:0}},severity:1,message:e.message};for(let i of t)this.finalizeDiagnostic(i,[r]);return}this.broadcastToClients({jsonrpc:k,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Es=class{uri;messages=[];receivedTypes=new Set;uniqueMessages=new Set;isFromEditor=!1;constructor(e){this.uri=e}setReceivedType(e){this.receivedTypes.add(e)}addMessage(e,t){this.receivedTypes.add(e);let r=`${e}:${t}`;if(this.uniqueMessages.has(r)){f.info(`[LegacyDiagnostic] addMessage: duplicate message=${r}`);return}this.uniqueMessages.add(r),this.messages.push(new ll(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)}},ll=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var _P={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"},FP={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing"},T={..._P,...FP},Zt={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"},bm=new Set([1e3,2e3,3e3,3001]);function jP(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function HP(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function $P(n){return D(n)&&typeof n.moduleName=="string"&&typeof n.current=="number"&&typeof n.total=="number"?`indexing module '${n.moduleName}', ${n.current} of total ${n.total} modules`:`params=${JSON.stringify(n??null)}`}var bs=class n{client;isInitialized=!1;stopOnce=null;callbacks=new mr;requestCallbacks=new Xt;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new Kt(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.EXIT,params:{}}),Zt.EXIT),f.info("[LegacyClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),f.info("[LegacyClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(T.BROADCAST),this.callbacks.register(T.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(T.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(T.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(T.INDEXING_PROGRESS_UPDATE,e)}registerRequestCallback(e,t){this.requestCallbacks.register(e,t)}sendInitialize(e,t){this.client.send("initialize",e,t)}sendInitialized(e){this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.INITIALIZED,params:{editors:e}}),Zt.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:k,id:0,result:{}}),Zt.EMPTY)}sendAsyncRequest(e,t,r,i){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!jP(t)){f.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof r!="number"){f.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(r)}`);return}let o=t.textDocument.uri,s=Qe(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!HP(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),T.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!D(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){f.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;f.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),Zt.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let i=Qe(t);e.textDocument.uri=i,f.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new Es(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,T.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),Zt.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=Qe(e.uri),r=this.diagnosticMap.get(t);r&&(r.clear(),this.registerDiagnosticTimeout(t,T.PUBLISH_DIAGNOSTICS)),f.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),Zt.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=Qe(e);f.info(`[LSP] didClose, uri: ${r}`);let i=this.diagnosticMap.get(r);if(!t&&(!i||i.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:k,method:T.DID_CLOSE,params:{textDocument:{uri:r}}}),Zt.DID_CLOSE)}getDiagnosticMessage(e){let t=Qe(e),r=this.diagnosticMap.get(t);return r?r.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let r=t instanceof Error?t.message:String(t);f.error(`[LSP] JSON parse error: ${r}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let r=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,T.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:k,method:T.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t,e)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e,t){switch(e){case T.MODULE_INIT_FINISH:return f.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(T.MODULE_INIT_FINISH),this.callbacks.unregister(T.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case T.INDEXING_PROGRESS_UPDATE:return f.info(`[LSP] onIndexingProgressUpdate: ${$P(t.params)}`),this.callbacks.invoke(T.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case T.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case T.ON_PACKAGE_CHANGE_FINISH:f.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case T.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case T.ON_ASYNC_HOVER:this.handleAsyncResponse(t,T.HOVER);return;case T.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,T.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case T.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,T.REFERENCES);return;default:f.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){f.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;D(t)&&D(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){f.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,r={jsonrpc:k,method:T.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){f.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(r);return}if(!(t.length>0&&t[0]===!0)){f.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(r);return}f.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){f.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let r=e.params;if(!D(r)){f.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=r.requestId;if(typeof i!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,r)}handleForceOpenFile(e){if(!e){f.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,T.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){f.info("[LSP] publishDiagnostics uri is null");return}let r=e.version??-1;if(r===-1)return;let i=this.diagnosticMap.get(t);if(!i){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(r,JSON.stringify(s))}):i.setReceivedType(r),i.hasReceivedAllTypes(bm)&&this.finalizeDiagnostic(t,T.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){let t=e;if(delete t.source,t.severity!==void 0){let r=typeof t.severity=="number"?t.severity:parseInt(t.severity),o={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=o,t.severity=o}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),i=r?r.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,i){let o={uri:e,diagnostics:r,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import dl from"path";import*as ks from"path";var Ps=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var Cs=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Is=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var As=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ds=class{typeSetting=new Is;parameterNames=new As};var Rs=class{constructor(e,t,r,i){this.rootUri=e;this.lspServerWorkspacePath=U(ks.dirname(t)),this.indexingDataLocation=U(i),this.loggerPath=U(ks.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Ps;gutterIconsSetting=new Cs;inlayHintsSetting=new Ds;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Pm from"path";var Ci=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(U(Pm.join(e,"src","main","resources")))}};var UP="OS",hr=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${UP}`;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 Ci(e)):this.buildProfileParam=new Ci}toString(){return JSON.stringify(this)}};var gr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Ge from"path";import*as vr from"fs";var Ts=class{modulePath;dependencies={};dynamicDependencies={}};var Nn=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 yr=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 Rt from"path";import*as xs from"fs";var wr=class{name="";version="";storePath="";dependencyPath="";path=""};var L={HVIGOR_CACHE:".hvigor",DEPENDENCY:"dependencyMap",JSON5:".json5",KEY_DEPENDENCY:"dependencies",KEY_DYNAMIC_DEPENDENCY:"dynamicDependencies",KEY_DEV_DEPENDENCY:"devDependencies",OH_MODULES_PATH:"oh_modules",OHPM_PATH:".ohpm",LOCK_JSON5_FILE:"lock.json5",OH_PACKAGE_JSON5:Xe.OH_PACKAGE_JSON5},Ii=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,Ln=`${L.DEPENDENCY}${L.JSON5}`,fU=Xe.SYNC_OUTPUT_PATH;var Ai=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Rt.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=Te(t);r&&(this.dependencies=this.getDependencyList(r,L.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(r,L.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(r,L.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let r=[];if(!D(e))return r;let i=e[t];if(!D(i))return r;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){f.error(`${o} package dependency value is not String ${t}`);continue}let a=new wr;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,i){if(!(!e||!t))try{let o=Rt.normalize(Rt.join(this.modulePath,L.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=o;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=o;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Rt.isAbsolute(s)){r.dependencyPath=o;return}if(!i){let a=Rt.resolve(this.modulePath,s);o=v.ensurePathWithinRoot(this.projectPath,a)}xs.existsSync(o)&&xs.statSync(o).isDirectory()&&(r.dependencyPath=o)}catch(o){f.error("parser dependency path is invalid",o)}}};import*as On from"fs";import*as Di from"path";import BP from"json5";var Ns=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";static MAX_LOCK_FILE_SIZE=20*1024*1024;static MAX_KEYS_PER_OBJECT=5e4;static MAX_JSON_DEPTH=50;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 Di.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}static checkObjectDepth(e,t,r=0){if(r>t)return!1;if(typeof e!="object"||e===null)return!0;if(Array.isArray(e)){for(let i of e)if(!n.checkObjectDepth(i,t,r+1))return!1;return!0}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&!n.checkObjectDepth(e[i],t,r+1))return!1;return!0}readLockFile(e){if(!On.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=On.statSync(e);if(t.size>n.MAX_LOCK_FILE_SIZE)return f.error(`lock file is too large (${t.size} bytes), read aborted`),this.clearDependencies(),null}catch(t){return f.error(`Failed to stat lock file: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}try{let t=On.readFileSync(e,"utf8"),r=BP.parse(t);return r?n.checkObjectDepth(r,n.MAX_JSON_DEPTH)?r:(f.error("lock.json5 nesting depth exceeds limit"),this.clearDependencies(),null):(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error(`Error parsing lock.json5: ${t instanceof Error?t.message:String(t)}`),this.clearDependencies(),null}}validateLockFile(e){if(!D(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,L.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,L.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,L.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;let r=0;for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;let o=e[i];if(!D(o)){f.error(`${i} value is not json object`);continue}if(++r>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 packages object exceeds key limit, truncating");break}typeof o.storePath=="string"&&t.set(i,o.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];let i=0;for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(++i>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 modules object exceeds key limit, truncating");break}let s=e[o];if(D(s)){let a=typeof s.name=="string"?s.name:"";if(r==="."&&a===""||a===r)return this.getFinalDependencyList(e,t,o)}}return[]}getFinalDependencyList(e,t,r){let i=e[r];if(!D(i))return f.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!D(s))return[];let a=0;for(let c in s){if(!Object.prototype.hasOwnProperty.call(s,c))continue;if(++a>n.MAX_KEYS_PER_OBJECT){f.warn("lock.json5 dependencies object exceeds key limit, truncating");break}let l=s[c];if(!D(l))continue;let d=typeof l.specifier=="string"?l.specifier:"",g=typeof l.version=="string"?l.version:"",w=new wr;w.name=c,w.version=g.startsWith(n.FILE_DEPENDENCY_PREFIX)?g.substring(n.FILE_DEPENDENCY_PREFIX.length):g,this.parseDependencyPath(w,r,c,d,g);let P=`${c}@${g}`;this.storePathMap.has(P)&&(w.storePath=this.storePathMap.get(P)||""),o.push(w)}return o}parseDependencyPath(e,t,r,i,o){let s=v.resolvePathWithinRoot(this.projectPath,Di.join(t,L.OH_MODULES_PATH,r));try{let a=o.startsWith(n.FILE_DEPENDENCY_PREFIX)?o.substring(n.FILE_DEPENDENCY_PREFIX.length):o,c=Di.isAbsolute(a)?v.ensurePathWithinRoot(this.projectPath,a):v.resolvePathWithinRoot(this.projectPath,a);On.existsSync(c)?(e.path=i,e.dependencyPath=this.fileNameForOhpm.test(o)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5, msg:",a instanceof Error?a.message:String(a))}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function Cm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Mn=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=Ge.join(t,Ii),i=Ge.join(r,Ln);if(!vr.existsSync(r)||!vr.existsSync(i)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let o=new yr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:c}}let a=Date.now();for(let c=0;c<s.length;c++){let l=s[c];Cm(l)&&(this.parseSingleModule(l,r,o,e),(c+1)%100===0&&f.info(`[Parser] getAllDependencyMap progress: ${c+1}/${s.length} (${Date.now()-a}ms)`))}return f.info(`[Parser] getAllDependencyMap parsed ${e.length} modules in ${Date.now()-a}ms`),{status:"OK"}}getDependenciesOnly(e){let t=[],r=this.projectPath,i=Ge.join(r,Ii),o=Ge.join(i,Ln);if(!vr.existsSync(i)||!vr.existsSync(o))return f.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(l=>l.trim()).filter(Boolean)):null,a=new yr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return f.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let l of c){if(!Cm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let g=v.resolvePathWithinRoot(this.projectPath,l.srcPath),w=Ge.join(i,d),P=U(g),O=this.buildModuleDependencies(d,P,w,a);O.moduleName=d,t.push(O)}return t}parseSingleModule(e,t,r,i){let o=e.name,s=v.resolvePathWithinRoot(this.projectPath,e.srcPath),a=Ge.join(t,o),c=U(s),l=new hr(c),d=this.buildModuleDependencies(o,c,a,r);this.parseModuleJson5(c,l);let g=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=o,l.moduleType=o,l.packageName=o,l.moduleDependencies=d,l.moduleJsonParam=new gr(g),i.push(l)}buildModuleDependencies(e,t,r,i){let o=new yr(this.projectPath,e,t);Ai.getInstance(r,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Ts;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let r={},i={};for(let o of e.finalDependencies)r[o.name]=new Nn(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Nn(o);t.dependencies=r,t.dynamicDependencies=i}parseProjectDependencies(e,t){let r=Ge.join(e,L.OH_PACKAGE_JSON5);if(!vr.existsSync(r))return;Ai.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 Ns(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Ge.join(e,"src","main","module.json5"),i=Te(r);if(!D(i)||!D(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(D(e)&&Array.isArray(e.requestPermissions))for(let r of e.requestPermissions)D(r)&&typeof r.name=="string"&&t.push(r.name);return t}parseMainPages(e){let t=Ge.join(e,"src","main","resources","base","profile","main_pages.json"),r=Te(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=this.getSdkPkg();if(!(!D(t)||!D(t.data))){if(typeof t.data.apiVersion=="string"){let r=parseInt(t.data.apiVersion,10);!Number.isNaN(r)&&r>=26&&typeof t.data.platformVersion=="string"?e.compileSdkLevel=t.data.platformVersion:e.compileSdkLevel=t.data.apiVersion}typeof t.data.releaseType=="string"&&(e.compileSdkType=t.data.releaseType),typeof t.data.version=="string"&&(e.compileSdkVersion=t.data.version)}}getSdkPkg(){if(this.sdkPkgCache===void 0){let e=Ge.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=Te(e)}return this.sdkPkgCache}parseCompatibleSdkVersion(e){let t=this.getBuildProfile();if(!D(t)||!D(t.app)||!Array.isArray(t.app.products)||t.app.products.length===0)return;let r=t.app.products[0];if(!D(r)||typeof r.compatibleSdkVersion!="string")return;let[i,o]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=i,e.compatibleSdkLevel=o}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Ge.join(this.projectPath,"build-profile.json5");this.buildProfileCache=Te(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),i=e.substring(t+1,e.length-1);return[r,i]}parseDeviceTypes(e){return!D(e)||!Array.isArray(e.deviceTypes)?[]:e.deviceTypes.filter(t=>typeof t=="string").map(t=>this.getDeviceType(t))}getDeviceType(e){return{liteWearable:1,wearable:2,tv:3,car:4,phone:5,default:5,smartVision:6,tablet:7,router:8,pc:9,"2in1":10}[e]||0}};var Ls=class{constructor(e=[]){this.valueSet=e}valueSet};var Sr=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Im=(b=>(b[b.File=1]="File",b[b.Module=2]="Module",b[b.Namespace=3]="Namespace",b[b.Package=4]="Package",b[b.Class=5]="Class",b[b.Method=6]="Method",b[b.Property=7]="Property",b[b.Field=8]="Field",b[b.Constructor=9]="Constructor",b[b.Enum=10]="Enum",b[b.Interface=11]="Interface",b[b.Function=12]="Function",b[b.Variable=13]="Variable",b[b.Constant=14]="Constant",b[b.String=15]="String",b[b.Number=16]="Number",b[b.Boolean=17]="Boolean",b[b.Array=18]="Array",b[b.Object=19]="Object",b[b.Key=20]="Key",b[b.Null=21]="Null",b[b.EnumMember=22]="EnumMember",b[b.Struct=23]="Struct",b[b.Event=24]="Event",b[b.Operator=25]="Operator",b[b.TypeParameter=26]="TypeParameter",b))(Im||{}),Am=()=>Object.values(Im).filter(n=>typeof n=="number");var Os=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Ms=class{applyEdit=!0;workspaceEdit=new Os;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ls(Am());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Sr;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var _s=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Fs=class{constructor(e=[]){this.valueSet=e}valueSet};var js=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Dm=(C=>(C[C.Text=1]="Text",C[C.Method=2]="Method",C[C.Function=3]="Function",C[C.Constructor=4]="Constructor",C[C.Field=5]="Field",C[C.Variable=6]="Variable",C[C.Class=7]="Class",C[C.Interface=8]="Interface",C[C.Module=9]="Module",C[C.Property=10]="Property",C[C.Unit=11]="Unit",C[C.Value=12]="Value",C[C.Enum=13]="Enum",C[C.Keyword=14]="Keyword",C[C.Snippet=15]="Snippet",C[C.Color=16]="Color",C[C.File=17]="File",C[C.Reference=18]="Reference",C[C.Folder=19]="Folder",C[C.EnumMember=20]="EnumMember",C[C.Constant=21]="Constant",C[C.Struct=22]="Struct",C[C.Event=23]="Event",C[C.Operator=24]="Operator",C[C.TypeParameter=25]="TypeParameter",C))(Dm||{}),Rm=()=>Object.values(Dm).filter(n=>typeof n=="number");var Hs=class{completionItemKind=new Fs(Rm());completionItem=new js;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var $s=class{synchronization=new _s;completion=new Hs;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 Sr;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var Us=class{workspace=new Ms;textDocument=new $s;notebookDocument=null;window=null;general=null;experimental=null};var Bs=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var Ws=class{constructor(e,t,r,i,o,s=!0){this.sdkPath=e;this.rootUri=r;this.nodeMaxOldSpaceSize=o;this.useStandardProtocol=s;this.serverPath=zr(t,this.useStandardProtocol),this.logPath=Su(),this.indexLogPath=i||this.logPath;let a={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath};this.messageHandle=this.useStandardProtocol?new Ss(a):new bs(a),this.messageHandle.setBroadcastToClients(c=>this.onLspMessage(c))}sdkPath;rootUri;nodeMaxOldSpaceSize;useStandardProtocol;messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let i=Qe(this.rootUri),o=new Rs(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Mn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s;let l=No(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new Bs(i,o,new Us),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,Fe),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:k,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:k,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((i,o)=>{r.onIndexingProgressUpdate(o),r.onInitializationCompleted(i)},"LSP initialization",Fe),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){f.info(`[LSP] registerDiagnosticCallback uri='${e}', useStandardProtocol=${this.useStandardProtocol}`),this.messageHandle.registerRequestCallback(e,(t,r)=>{let i=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let o={jsonrpc:k,method:t,params:{uri:typeof i.uri=="string"?i.uri:e,diagnostics:Array.isArray(i.diagnostics)?i.diagnostics:[],...typeof i.errorMessage=="string"?{errorMessage:i.errorMessage}:{}}};this.onLspMessage(o)})}async hover(e){let t=e.textDocument.uri;return this.registerDiagnosticCallback(t),this.stdHandle.sendLspRequest(y.HOVER,e)}async definition(e){return this.stdHandle.sendLspRequest(y.DEFINITION,e)}async references(e){return this.stdHandle.sendLspRequest(y.REFERENCES,e)}async completion(e){return this.stdHandle.sendLspRequest(y.COMPLETION,e)}async documentSymbol(e){return this.stdHandle.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async diagnostic(e){return this.stdHandle.sendLspRequest(y.DIAGNOSTIC,e,120*1e3)}async sendFeatureRequest(e,t){return this.stdHandle.sendLspRequest(e,t)}reloadDependenciesOnly(e){let t=e?.fullReload??!1,r=new Mn(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){f.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let l=r.getDependenciesOnly();this.markDependencyTypesIncremental(l);let d=this.mergeDepsOnlyIntoModuleList(l,i);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=r.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),this.sendDidChangeConfiguration({moduleSet:c}),f.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}sendDidChangeConfiguration(e){this.stdHandle.sendDidChangeConfiguration(e)}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),r=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,r),c=i.dependencies??{},l=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,g)=>{(i.dependencies??={})[d]=this.makeDeleteEntry(d,g)}),this.markAddAndDeleteInDeps(a,l,(d,g)=>{(i.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,g)})}}getOldDepsForModule(e,t,r){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||r(i,e[i])}makeDeleteEntry(e,t){return new Nn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new hr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new gr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let i=new Map(r.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=qn(dl.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=qn(dl.join(t,"default/openharmony/ets/api")),o=qn(dl.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:k,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:k,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:k,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:k,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:k,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:k,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!vm(e)){f.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case y.DID_OPEN:this.handleDidOpenNotification(e);break;case y.DID_CHANGE:this.handleDidChangeNotification(e);break;case y.DID_CLOSE:this.handleDidCloseNotification(e);break;case y.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;case y.DID_CREATE_FILES:this.handleDidCreateFiles(e);break;case y.DID_DELETE_FILES:this.handleDidDeleteFiles(e);break;default:f.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didOpen params");return}this.stdHandle.sendDidOpen(t)}handleDidChangeNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didChange params");return}this.stdHandle.sendDidChange(t)}handleDidCloseNotification(e){let t=e.params;if(!t||!t.textDocument||typeof t.textDocument.uri!="string"){f.error("Invalid textDocument/didClose params");return}this.stdHandle.closeFile(t)}handleDidChangeWatchedFiles(e){let t=e.params;!t||!Array.isArray(t.changes)||this.messageHandle.onDidChangeWatchedFiles(t.changes)}handleDidCreateFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_CREATE_FILES,t)}handleDidDeleteFiles(e){let t=e.params;!t||!Array.isArray(t.files)||this.stdHandle.sendNotification(y.DID_DELETE_FILES,t)}async dispose(){await this.messageHandle.stop()}};import*as kt from"fs";import*as Qt from"path";import{createHash as GP}from"crypto";import{EventEmitter as VP}from"events";var Gs=class extends VP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let i of t)r.has(i)||this.watchFile(i);for(let i of r)t.has(i)||(this.unwatchFile(i),f.info(`[ConfigFileWatcher] Stopped watching: ${i}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!kt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=kt.watch(t,r=>{r==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",r=>{f.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${r.message}`)}),f.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${r instanceof Error?r.message:String(r)}`)}}emitModuleAddedEvents(t,r){for(let i of t){let o=v.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:r,moduleName:i.name})}}emitModuleRemovedEvents(t,r){for(let i of t){let o=v.resolvePathWithinRoot(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:r,removedModuleName:i.name})}}emitModuleRenamedEvents(t,r){for(let i of t){let o=v.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,r){for(let i of t){let o=v.resolvePathWithinRoot(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:r,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,f.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,r){let i=this.buildModuleMatchState(r),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(r,i,o),o}buildModuleMatchState(t){let r=new Map,i=new Map;for(let o of t)r.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:i}}matchExactModules(t,r){for(let i of t){let o=r.newBySrc.get(i.srcPath);o&&o.name===i.name&&(r.matchedOld.add(i),r.matchedNew.add(o))}}matchRenamedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newBySrc.get(o.srcPath);s&&!r.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}matchMovedModules(t,r,i){for(let o of t){if(r.matchedOld.has(o))continue;let s=r.newByName.get(o.name);s&&!r.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),r.matchedOld.add(o),r.matchedNew.add(s))}}collectRemovedModules(t,r,i){for(let o of t)r.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,r,i){for(let o of t)r.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=Te(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Qt.join(this.projectRoot,L.OH_PACKAGE_JSON5);kt.existsSync(r)&&t.push(r);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=v.resolvePathWithinRoot(this.projectRoot,o.srcPath),a=Qt.join(s,L.OH_PACKAGE_JSON5);kt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Qt.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=kt.readFileSync(t,"utf-8");return GP("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let i=kt.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(r){f.error(`[ConfigFileWatcher] Failed to watch ${t}: ${r instanceof Error?r.message:String(r)}`)}}unwatchFile(t){let r=this.watchers.get(t);r&&(r.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Qt.basename(t),relativePath:Qt.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as en from"fs";import*as nt from"path";import{createHash as zP}from"crypto";import{EventEmitter as qP}from"events";var Vs=class extends qP{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=nt.join(t,Ii)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!en.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=en.watch(this.depMapDir,{recursive:!0},(t,r)=>this.onDirEvent(t,r)),this.dirWatcher.on("error",t=>{f.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){f.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),f.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return U(nt.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let i=r.replace(/\\/g,"/"),o;if(i===L.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Ln)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=nt.join(this.depMapDir,r);en.existsSync(s)&&this.scheduleDebouncedFullScan()}stop(){this.dirWatcher&&(this.dirWatcher.close(),this.dirWatcher=null),this.fullScanTimer&&(clearTimeout(this.fullScanTimer),this.fullScanTimer=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.coalesceTimer&&(clearTimeout(this.coalesceTimer),this.coalesceTimer=null),this.pendingTags=[],this.pendingRenames=[],this.contentHashes.clear(),this.initialScanDone=!1,f.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=nt.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=nt.join(this.depMapDir,Ln),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...i.map(s=>({path:nt.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!en.existsSync(s))continue;let c=this.canonicalPath(s),l=this.computeFileHash(s);if(!l)continue;let d=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,l);continue}d!==l&&(this.contentHashes.set(c,l),f.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=nt.join(this.depMapDir,Ln);try{let r=Te(t);if(typeof r!="object"||r===null)return[];let i=r.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${r instanceof Error?r.message:String(r)}`),[]}}scheduleCoalescedReload(t){this.pendingTags.push(t),t==="dep-map-json"&&this.applyDepMapJsonDiff(),this.coalesceTimer&&clearTimeout(this.coalesceTimer),this.coalesceTimer=setTimeout(()=>{this.coalesceTimer=null,this.flushPendingReload()},this.coalesceMs)}collectPendingState(){let t=this.pendingTags,r=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:r}}processTagsIntoSets(t,r,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of r)i.add(o.info.newName);return i}emitIncrementalReload(t,r,i,o,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(f.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${r.length}`),t.includes("root-oh-package")){f.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(r,i,o,s,a);for(let l of o)s.delete(l);if(o.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return U(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:r,bySrcPath:i}}detectModuleRenames(t,r,i,o){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let l=nt.join(this.depMapDir,a.name,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(l)),f.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,r,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,i){for(let[o]of t)i.has(o)||r.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,r,i){for(let[o]of t)if(!i.has(o)&&!r.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=nt.join(this.depMapDir,o,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),r=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(r,o,a,c),this.detectAddedModules(o,r,c),this.detectRemovedModules(r,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=en.readFileSync(t,"utf-8");return zP("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as YP}from"child_process";import*as ul from"fs";import*as Ri from"path";var JP=["install","--all"];function KP(n){let e=n.replace(/sdk\/?$/i,"tools"),t=Ri.join(e,"ohpm","bin","pm-cli.js");if(ul.existsSync(t))return t;let r=n.toLowerCase().endsWith("sdk")?Ri.dirname(n):n;return t=Ri.join(r,"ohpm","bin","pm-cli.js"),ul.existsSync(t)?t:null}async function XP(n,e,t,r){return new Promise(i=>{let o=YP(n,[e,...JP],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1275
1275
|
`);i({exitCode:c??-1,output:l})}),o.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1276
1276
|
`);i({exitCode:-1,output:l+`
|
|
1277
|
-
`+c.message})})})}function BP(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Im(n,e){try{let t=Ao(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=$P(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await UP(t,r,n,e);return BP(o),i===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),f.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Am={UNINITIALIZED:-32099,UNKNOWN:-32e3},ki=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Am.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Am.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Er=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let i=r?.skipHvigorSync===!0,o=await go(e,async()=>await Im(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Cu(e,t)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return o.acquired?o.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Bs(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ki.uninitialized(t):ki.unknown();this.onMessage({jsonrpc:R,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:R,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Ws(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Gs(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:R,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var WP=10080*60*1e3,GP=7200*60*1e3,VP=120*1e3,br=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i}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:ul.object({files:ul.array(ul.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,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=ae(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Za(s,WP,"[ArkTS-Check]"),Za(o,GP,"[ArkTS-Check]")}),To(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}`),this.manager=new Er({sdkPath:l,arktsLangServerPath:t,workspaceRoot:U(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(_e),this.manager.start([]).catch(w=>{let P=w instanceof Error?w:new Error(String(w));this.failInit(P)})})}resolveProjectAndDeveco(){let e=St(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=Po(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol: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=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=Pn(e),i=await Le.promises.readFile(e,"utf8"),s=`deveco.apptool.${he.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return zP(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},VP);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1278
|
-
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.fetchTypeHierarchy(t,e.line,e.character,e.direction);return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async fetchTypeHierarchy(e,t,r,i){return this.withOpenFile(e,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:t,character:r}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=i==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let r=[];for(let i of t){let o=await this.manager.sendFeatureRequest(e,{item:i});Array.isArray(o)?r.push(...o):o&&r.push(o)}return r}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await
|
|
1279
|
-
`).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Pn(e),i=await
|
|
1277
|
+
`+c.message})})})}function ZP(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function km(n,e){try{let t=Do(e);if(!t)return f.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let r=KP(e);if(!r)return f.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await XP(t,r,n,e);return ZP(o),i===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),f.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Tm={UNINITIALIZED:-32099,UNKNOWN:-32e3},ki=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Tm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Tm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Er=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};onConfigChanged=null;disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let i=r?.skipHvigorSync===!0,o=await go(e,async()=>await km(e,t)?i?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Iu(e,t)?(f.info("[ArktsLspManager] syncProject completed successfully"),{status:"success"}):(f.error("[ArktsLspManager] syncProject failed"),{status:"failed",reason:"hvigor sync failed"}):(f.error("[ArktsLspManager] ohpm install failed"),{status:"failed",reason:"ohpm install failed"}));return o.acquired?o.result:(f.info("[ArktsLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){f.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){f.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Ws(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize,this.config.useStandardProtocol);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:k,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?ki.uninitialized(t):ki.unknown();this.onMessage({jsonrpc:k,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:k,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new Gs(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Vs(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){f.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let r=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.onMessage({jsonrpc:k,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var QP=10080*60*1e3,eC=7200*60*1e3,tC=120*1e3,br=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;sdkPath;arktsLangServerPath;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r,i){this.projectPath=e,this.sdkPath=t,this.arktsLangServerPath=r,this.nodeMaxOldSpaceSize=i}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:pl.object({files:pl.array(pl.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,arktsLangServerPath:t,useStandardProtocol:r}=this.resolveProjectAndDeveco();this.useStandardProtocol=r;let i=ae(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Qa(s,QP,"[ArkTS-Check]"),Qa(o,eC,"[ArkTS-Check]")}),xo(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a;h.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${c??"undefined \u2192 dynamic formula applies"}`);let l=this.sdkPath;h.info(`[ArktsCheck] sdkPath=${l}, arktsLangServerPath=${t}, useStandardProtocol=${r}`),this.manager=new Er({sdkPath:l,arktsLangServerPath:t,workspaceRoot:U(i),indexLogPath:s,nodeMaxOldSpaceSize:c,useStandardProtocol:r}),this.manager.setOnMessage(d=>this.handleLspMessage(d)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((d,g)=>{this.initResolve=d,this.initReject=g,this.armInitTimer(Fe),this.manager.start([]).catch(w=>{let P=w instanceof Error?w:new Error(String(w));this.failInit(P)})})}resolveProjectAndDeveco(){let e=vt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.arktsLangServerPath;if(!t)throw new Error("arkts-lang-server path not found");let r=Co(t);return h.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),{harmonyRoot:e,arktsLangServerPath:t,useStandardProtocol: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=this.manager;if(!t)throw new Error("ArktsLspManager not initialized");let r=Pn(e),i=await Ne.promises.readFile(e,"utf8"),s=`deveco.apptool.${he.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,i,s):this.checkFileLegacy(t,e,r,i,s)}async checkFileStandard(e,t,r,i){h.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:i,version:1}});try{h.debug(`textDocument/diagnostic uri=${t}`);let o=await e.diagnostic({textDocument:{uri:t}});return nC(o)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,i,o){let s=r;e.registerDiagnosticCallback(r);let a=new Promise((c,l)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(s)&&l(new Error("Wait for diagnostics timeout"))},tC);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});h.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${i.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:i,languageId:o,version:i.length},editorFiles:[r],isFromEditor:!1});try{return await a}finally{e.closeFileLegacy(r,!1)}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],r=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1278
|
+
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,r),this.formatCallResult(t,r))}async handleLspFeature(e,t){if(!this.initialized)return this.buildNotReadyResponse();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){let s=o instanceof Error?o.message:String(o);return h.error(`handleLspFeature ${e} failed: ${s}`),{content:[{type:"text",text:`${e} failed: ${s}`}],isError:!0}}}async handleWorkspaceSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();h.info(`handleWorkspaceSymbol: query="${e}"`);try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return{content:[{type:"text",text:t==null?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(t,null,2)}`}]}}catch(t){let r=t instanceof Error?t.message:String(t);return h.error(`handleWorkspaceSymbol failed: ${r}`),{content:[{type:"text",text:`workspaceSymbol failed: ${r}`}],isError:!0}}}async handleWorkspaceSymbolRaw(e){if(!this.initialized)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};h.info(`handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleDocumentSymbol failed: ${i}`),{content:[{type:"text",text:`documentSymbol failed: ${i}`}],isError:!0}}}async handleCallHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:o},position:{line:e.line,character:e.character}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],calls:[]};let c=e.direction==="incoming"?y.INCOMING_CALLS:y.OUTGOING_CALLS,l=[];for(let d of a){let g=await this.manager.sendFeatureRequest(c,{item:d});Array.isArray(g)?l.push(...g):g&&l.push(g)}return{items:a,calls:l}});return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){let i=r instanceof Error?r.message:String(r);return h.error(`handleCallHierarchy failed: ${i}`),{content:[{type:"text",text:`callHierarchy failed: ${i}`}],isError:!0}}}async handleCodeAction(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleCodeAction: file=${t} line=${e.line} char=${e.character}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};return this.manager.sendFeatureRequest(y.CODE_ACTION,{textDocument:{uri:o},range:{start:s,end:s},context:{diagnostics:[]}})});return{content:[{type:"text",text:r==null?"codeAction: no result":`codeAction: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("codeAction",r)}}async handleRename(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleRename: file=${t} line=${e.line} char=${e.character} newName=${e.newName}`);try{let r=await this.withOpenFile(t,async o=>{let s={line:e.line,character:e.character};if(await this.manager.sendFeatureRequest(y.PREPARE_RENAME,{textDocument:{uri:o},position:s})==null)throw new Error("Symbol at this position cannot be renamed");return this.manager.sendFeatureRequest(y.RENAME,{textDocument:{uri:o},position:s,newName:e.newName})});return{content:[{type:"text",text:r==null?"rename: no result":`rename: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("rename",r)}}async handleTypeHierarchy(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e.file}`}],isError:!0};h.info(`handleTypeHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.fetchTypeHierarchy(t,e.line,e.character,e.direction);return{content:[{type:"text",text:`typeHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("typeHierarchy",r)}}async handleCompletionItemResolve(e){if(!this.initialized)return this.buildNotReadyResponse();h.info("handleCompletionItemResolve");try{let t=await this.manager.sendFeatureRequest(y.COMPLETION_ITEM_RESOLVE,{item:e});return{content:[{type:"text",text:t==null?"completionItemResolve: no result":`completionItemResolve: ${JSON.stringify(t,null,2)}`}]}}catch(t){return this.buildErrorResponse("completionItemResolve",t)}}async fetchTypeHierarchy(e,t,r,i){return this.withOpenFile(e,async o=>{let s=await this.manager.sendFeatureRequest(y.PREPARE_TYPE_HIERARCHY,{textDocument:{uri:o},position:{line:t,character:r}}),a=Array.isArray(s)?s:s?[s]:[];if(a.length===0)return{items:[],results:[]};let c=i==="supertypes"?y.SUPERTYPES:y.SUBTYPES,l=await this.collectHierarchyItems(c,a);return{items:a,results:l}})}async collectHierarchyItems(e,t){let r=[];for(let i of t){let o=await this.manager.sendFeatureRequest(e,{item:i});Array.isArray(o)?r.push(...o):o&&r.push(o)}return r}async handleInlayHint(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let i=(await Ne.promises.readFile(t,"utf8")).split(`
|
|
1279
|
+
`).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=Pn(e),i=await Ne.promises.readFile(e,"utf8"),s=`deveco.apptool.${he.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=he.isAbsolute(e)?e:he.join(this.projectPath,e);return!Ne.existsSync(t)||!Ne.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=he.resolve(this.projectPath),i=[];for(let o of e){let s=v.isPathContained(o,r);if(!s.contained){t.push(`\u6587\u4EF6\u8DEF\u5F84\u8D8A\u6743: ${s.reason}`);continue}let a=he.resolve(he.isAbsolute(o)?o:he.join(r,o));if(!Ne.existsSync(a)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!Ne.statSync(a).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!a.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(a)}return i}async runDiagnosticsForFiles(e,t,r){for(let i of e){await pu(500);try{let o=await this.checkFile(i);r.push(rC(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
|
|
1280
1280
|
`)),t.length>0&&r.push(t.join(`
|
|
1281
1281
|
`));let i=r.join(`
|
|
1282
|
-
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(
|
|
1283
|
-
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await
|
|
1282
|
+
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(Fe),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=he.join($t(),"ArkTSCheck"),r=he.join(t,"mapping-config.properties"),i=fu(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=he.join(t,"lsp-log",String(i),o),a=he.join(t,"lsp-index",String(i));return Ne.mkdirSync(s,{recursive:!0}),Ne.mkdirSync(a,{recursive:!0}),{logPath:ae(s),indexPath:ae(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function nC(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function rC(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import*as tn from"fs";import*as _n from"path";import{z as fl}from"zod";function Pr(){return{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0}}function zs(n,e){let t=e instanceof Error?e.message:String(e);return h.error(`[CppLsp] ${n} failed: ${t}`),{content:[{type:"text",text:`${n} failed: ${t}`}],isError:!0}}var iC=500,Cr=class{manager;constructor(e){this.manager=e}static getToolDefinition(){return{name:"check_cpp_files",description:"Perform static syntax checks on the provided C/C++ files and return clangd diagnostics.",inputSchema:fl.object({files:fl.array(fl.string()).describe('List of C/C++ file paths to check, format: ["file1.cpp","file2.hpp",...]')})}}async handleCall(e){if(!this.manager.ready)return Pr();let t=[],r=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1283
|
+
`):"No valid C/C++ files"}],isError:!0};for(let c of i){await sC(iC);try{let l=await this.checkFile(c);r.push(oC(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let o=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1284
1284
|
`)),r.length>0&&s.push(r.join(`
|
|
1285
1285
|
`));let a=s.join(`
|
|
1286
|
-
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Pn(e),r=await tn.promises.readFile(e,"utf8"),i=Io(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=_n.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=E.isPathContained(o,r);if(!s.contained){t.push(`Path traversal detected: ${s.reason}`);continue}let a=_n.resolve(_n.isAbsolute(o)?o:_n.join(r,o));if(!tn.existsSync(a)){t.push(`File does not exist: ${o}`);continue}if(!tn.statSync(a).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!bn(a)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(tn.realpathSync(a))}catch{i.push(a)}}return i}};function JP(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function KP(n){return new Promise(e=>setTimeout(e,n))}import*as Ar from"fs";import*as zs from"path";var Ir=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Pr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return Vs(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Pr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return Vs("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Pr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return Vs("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Pn(e),i=await Ar.promises.readFile(e,"utf8"),o=Io(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=zs.isAbsolute(e)?e:zs.join(this.manager.projectRoot,e);return!Ar.existsSync(t)||!Ar.statSync(t).isFile()||!bn(t)?null:t}};import{spawn as XP}from"child_process";import*as Ys from"fs";import*as Dm from"path";var ZP=30*1e3,QP=30*1e3,qs=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Xt;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Kt(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,i,_e),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},QP);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${U(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=XP(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=qn(this.config.workspaceRoot),t=Qe(e),r=Dm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.11"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=ZP){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:R,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:R,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:R,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Ys.existsSync(this.config.logPath)||Ys.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),Qe(r)}}catch{}return e}};import*as Ti from"path";import*as fl from"fs";var xi=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(In(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await go(e,async()=>{try{return await Du(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return i.acquired?i.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(_e);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=St(this.config.workspaceRoot);this.resolvedRoot=e?ae(e):ae(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();To(t);let r=Co(this.config.sdkPath);if(!r){let s=`clangd executable not found under sdk: ${this.config.sdkPath}`;f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=Ti.dirname(qr(this.resolvedRoot));try{fl.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new qs({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Ti.join(Ut(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Ti.join(e,"lsp-log",t);return fl.mkdirSync(r,{recursive:!0}),ae(r)}catch{return"auto"}}};function Rm(n){let e=wo(n);return f.info(`[SyncGuard] ${e.reason}`),e}var gl=(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))(gl||{}),km=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(km||{}),gt=3,ml=600*1e3,hl=100,Js=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e={}){this.config=e,Cn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=St(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0;let o=bo(this.config.devecoPath);this.sdkPath=o.sdkPath,this.arktsLangServerPath=o.arktsLangServerPath,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}'`),this.server=new eC({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=al(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:se.object({target:se.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:se.object({files:se.array(se.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=se.object({file:se.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:se.number().describe("Line number (0-based)"),character:se.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:se.object({query:se.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:se.object({file:se.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:se.object({file:se.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:se.number().describe("Line number (0-based)"),character:se.number().describe("Character offset in the line (0-based)"),direction:se.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Po(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=E.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
|
|
1287
|
-
`)}],isError:!0}:null}let r=e.filter(i=>
|
|
1288
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(g=>typeof g=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>
|
|
1286
|
+
`).trim();return!o&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:o}}async checkFile(e){let t=Pn(e),r=await tn.promises.readFile(e,"utf8"),i=Ao(e),o=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:i,version:r.length}}});try{return await o}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=_n.resolve(this.manager.projectRoot),i=[];for(let o of e){let s=v.isPathContained(o,r);if(!s.contained){t.push(`Path traversal detected: ${s.reason}`);continue}let a=_n.resolve(_n.isAbsolute(o)?o:_n.join(r,o));if(!tn.existsSync(a)){t.push(`File does not exist: ${o}`);continue}if(!tn.statSync(a).isFile()){t.push(`Not a regular file: ${o}`);continue}if(!bn(a)){t.push(`Not a supported C/C++ file: ${o}`);continue}try{i.push(tn.realpathSync(a))}catch{i.push(a)}}return i}};function oC(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}function sC(n){return new Promise(e=>setTimeout(e,n))}import*as Ar from"fs";import*as qs from"path";var Ir=class n{manager;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION};constructor(e){this.manager=e}async handleLspFeature(e,t){if(!this.manager.ready)return Pr();let r=this.resolveSingleFile(t.file);if(!r)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${t.file}`}],isError:!0};let i=n.FEATURE_METHOD_MAP[e];if(!i)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let o=await this.withOpenFile(r,async a=>{let c={textDocument:{uri:a},position:{line:t.line,character:t.character}};return e==="references"&&(c.context={includeDeclaration:!0}),this.manager.sendFeatureRequest(i,c)});return{content:[{type:"text",text:o==null?`${e}: no result`:`${e}: ${JSON.stringify(o,null,2)}`}]}}catch(o){return zs(e,o)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return h.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Pr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};h.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return zs("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Pr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};h.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,o=>this.fetchCallHierarchyResult(o,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return zs("callHierarchy",r)}}async fetchCallHierarchyResult(e,t){let r=await this.manager.sendFeatureRequest(y.PREPARE_CALL_HIERARCHY,{textDocument:{uri:e},position:{line:t.line,character:t.character}}),i=this.normalizeCallHierarchyItems(r);if(i.length===0)return{items:[],calls:[]};let o=await this.collectIncomingCalls(i);return{items:i,calls:o}}normalizeCallHierarchyItems(e){return Array.isArray(e)?e:e?[e]:[]}async collectIncomingCalls(e){let t=[];for(let r of e)t.push(...await this.fetchIncomingCalls(r));return t}async fetchIncomingCalls(e){let t=await this.manager.sendFeatureRequest(y.INCOMING_CALLS,{item:e});return Array.isArray(t)?t:t?[t]:[]}async withOpenFile(e,t){let r=Pn(e),i=await Ar.promises.readFile(e,"utf8"),o=Ao(e);h.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${o} len=${i.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:i,languageId:o,version:i.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=qs.isAbsolute(e)?e:qs.join(this.manager.projectRoot,e);return!Ar.existsSync(t)||!Ar.statSync(t).isFile()||!bn(t)?null:t}};import{spawn as aC}from"child_process";import*as Js from"fs";import*as xm from"path";var cC=30*1e3,lC=30*1e3,Ys=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new Xt;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot};this.client=new Kt(r),this.client.on("message",o=>this.handleRawMessage(o)),this.client.on("error",o=>this.handleError(o)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let i=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,i,Fe),f.info("[ClangdLspProxy] initialize response received"),this.sendNotification(y.INITIALIZED,{}),t=!0}catch(r){this.lastStartErrorMessage=r instanceof Error?r.message:String(r),f.error(`[ClangdLspProxy] initialization failed: ${this.lastStartErrorMessage}`),await this.dispose()}e?.(t)}async hover(e){return this.sendLspRequest(y.HOVER,e)}async definition(e){return this.sendLspRequest(y.DEFINITION,e)}async declaration(e){return this.sendLspRequest(y.DECLARATION,e)}async references(e){return this.sendLspRequest(y.REFERENCES,e)}async implementation(e){return this.sendLspRequest(y.IMPLEMENTATION,e)}async documentSymbol(e){return this.sendLspRequest(y.DOCUMENT_SYMBOL,e)}async workspaceSymbol(e){return this.sendLspRequest(y.WORKSPACE_SYMBOL,e)}async prepareCallHierarchy(e){return this.sendLspRequest(y.PREPARE_CALL_HIERARCHY,e)}async incomingCalls(e){return this.sendLspRequest(y.INCOMING_CALLS,e)}async sendFeatureRequest(e,t){return this.sendLspRequest(e,t)}sendDidOpen(e){this.sendNotification(y.DID_OPEN,e)}sendDidChange(e){this.sendNotification(y.DID_CHANGE,e)}sendDidClose(e){this.sendNotification(y.DID_CLOSE,e)}sendNotification(e,t){if(!this.client){f.warn("[ClangdLspProxy] sendNotification before ready, dropped");return}this.client.sendNotification(e,t)}registerDiagnosticCallback(e){let t=this.normalizeClangdUri(e);if(this.diagnosticWaiters.has(t)){f.warn(`[ClangdLspProxy] overwrite existing diagnostic waiter for ${t}`);let r=this.diagnosticWaiters.get(t);clearTimeout(r.timer),this.diagnosticWaiters.delete(t)}return new Promise((r,i)=>{let o=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&i(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},lC);this.diagnosticWaiters.set(t,{resolve:r,reject:i,timer:o})})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){this.requestCallbacks.rejectAll(new Error("ClangdLspProxy disposing"));for(let[,e]of this.diagnosticWaiters)clearTimeout(e.timer),e.reject(new Error("ClangdLspProxy disposing"));if(this.diagnosticWaiters.clear(),this.client&&this.clangdProcess)try{await this.sendLspRequest(y.SHUTDOWN,null,3e3).catch(e=>{f.warn(`[ClangdLspProxy] shutdown request failed: ${e}`)}),this.sendNotification(y.EXIT,null),await this.client.waitForExitOrTimeout(300)}catch(e){f.warn(`[ClangdLspProxy] dispose error: ${e}`)}if(this.clangdProcess){try{this.clangdProcess.exitCode===null&&this.clangdProcess.signalCode===null&&this.clangdProcess.kill()}catch{}this.clangdProcess=null}this.client=null}spawnClangd(){let e=[`--compile-commands-dir=${U(this.config.compileCommandsDir)}`,"--log=info","--pch-storage=memory","--limit-results=100"];f.info(`[ClangdLspProxy] spawn: ${this.config.clangdPath} ${e.join(" ")}`);let t=aC(this.config.clangdPath,e,{cwd:this.config.workspaceRoot,stdio:["pipe","pipe","pipe"],windowsHide:!0});if(!t.stdin||!t.stdout||!t.stderr)throw new Error("Failed to spawn clangd: stdio not available");return t}buildInitializeParams(){let e=qn(this.config.workspaceRoot),t=Qe(e),r=xm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.13"},rootPath:e,rootUri:t,workspaceFolders:[{uri:t,name:r}],capabilities:this.buildClientCapabilities(),initializationOptions:null}}buildClientCapabilities(){return{textDocument:{synchronization:{didOpen:!0,didChange:!0,didClose:!0,willSave:!1,save:!1},publishDiagnostics:{relatedInformation:!0,versionSupport:!1,tagSupport:{valueSet:[1,2]}},hover:{contentFormat:["markdown","plaintext"]},completion:{contextSupport:!1,completionItemKind:{valueSet:[]}},signatureHelp:{signatureInformation:{documentationFormat:["markdown","plaintext"]}},references:{},declaration:{linkSupport:!0},definition:{linkSupport:!0},implementation:{linkSupport:!0},documentSymbol:{hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:[]}},callHierarchy:{dynamicRegistration:!1}},workspace:{symbol:{symbolKind:{valueSet:[]}},configuration:!1,didChangeWatchedFiles:{dynamicRegistration:!1}}}}sendLspRequest(e,t,r=cC){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let i=this.nextRequestId++,o=this.requestCallbacks.registerPending(i,e,r);return this.client.sendRequest(e,t,i),o}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let i=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${i}, raw: ${e.slice(0,200)}`);return}"id"in t&&("result"in t||"error"in t)?this.handleResponse(t):"method"in t?this.handleNotification(t):f.warn(`[ClangdLspProxy] unrecognized message: ${JSON.stringify(t).slice(0,200)}`)}handleResponse(e){let t=e.id;if(t==null||typeof t!="string"&&typeof t!="number")return;let r=t;if(e.error!==void 0){let i=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${i.code??-1} message=${i.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${i.code??-1}: ${i.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:k,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:k,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let i=Array.isArray(e.diagnostics)?e.diagnostics:[],o=i.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${o}`),r.resolve(i)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:k,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{Js.existsSync(this.config.logPath)||Js.mkdirSync(this.config.logPath,{recursive:!0})}catch{}}normalizeClangdUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=decodeURIComponent(t.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(r)&&(r=r.slice(1)),Qe(r)}}catch{}return e}};import*as Ti from"path";import*as ml from"fs";var xi=class{config;proxy=null;isInitialized=!1;onMessage=()=>{};disposeOnce=null;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;resolvedRoot="";constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}get ready(){return this.isInitialized&&this.proxy!==null}get projectRoot(){return this.resolvedRoot}async start(){if(!this.isInitialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.doStart();try{await this.initPromise}catch(e){throw this.initPromise=null,e}}}sendNotification(e){if(!this.proxy){f.warn("[ClangdLspManager] sendNotification before LSP ready, dropped");return}this.dispatchNotification(e)}async sendFeatureRequest(e,t){if(!this.proxy)throw new Error("[ClangdLspManager] LSP not ready");return this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e||!t)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};if(In(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let i=await go(e,async()=>{try{return await Ru(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(o){let s=o instanceof Error?o.message:String(o);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return i.acquired?i.result:(f.info("[ClangdLspManager] Build lock held by another process, skipping sync"),{status:"skipped",reason:"build lock held by another process"})}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}doStart(){return new Promise((e,t)=>{this.initResolve=e,this.initReject=t,this.armInitTimer(Fe);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=vt(this.config.workspaceRoot);this.resolvedRoot=e?ae(e):ae(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();xo(t);let r=Io(this.config.sdkPath);if(!r){let s=`clangd executable not found under sdk: ${this.config.sdkPath}`;f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let i=Ti.dirname(qr(this.resolvedRoot));try{ml.mkdirSync(i,{recursive:!0})}catch(s){f.warn(`[ClangdLspManager] Failed to create compile_commands dir: ${s}`)}f.info(`[ClangdLspManager] clangdPath: ${r}`),f.info(`[ClangdLspManager] workspaceRoot: ${this.resolvedRoot}`),f.info(`[ClangdLspManager] compileCommandsDir: ${i}`);let o=new Ys({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:i,logPath:t});o.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=o,o.start(s=>this.handleProxyInitialized(s)).catch(s=>{let a=s instanceof Error?s:new Error(String(s));this.handleProxyInitialized(!1,a.message)})}handleProxyInitialized=(e,t)=>{if(this.clearInitTimer(),e){this.isInitialized=!0,f.info("[ClangdLspManager] clangd initialized");let r=this.initResolve;this.clearInitHandlers(),r?.()}else{let r=t??this.proxy?.consumeStartErrorMessage()??"unknown error";f.error(`[ClangdLspManager] clangd initialization failed: ${r}`),this.isInitialized=!1,this.proxy=null;let i=this.initReject;this.clearInitHandlers(),i?.(new Error(`C++ LSP initialize failed: ${r}`))}};handleLspMessage(e){this.onMessage(e)}dispatchNotification(e){if(!this.proxy)return;let t=e,r=t.method;if(!r){f.warn("[ClangdLspManager] dispatchNotification: missing method");return}let i=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(i);break;case y.DID_CHANGE:this.proxy.sendDidChange(i);break;case y.DID_CLOSE:this.proxy.sendDidClose(i);break;default:this.proxy.sendNotification(r,i)}}armInitTimer(e){this.clearInitTimer(),this.initDeadlineTimer=setTimeout(()=>{this.failInit(new Error("C++ LSP initialize timeout"))},e)}clearInitTimer(){this.initDeadlineTimer&&(clearTimeout(this.initDeadlineTimer),this.initDeadlineTimer=null)}clearInitHandlers(){this.clearInitTimer(),this.initResolve=null,this.initReject=null}failInit(e){let t=this.initReject;this.clearInitHandlers(),t?.(e)}async performDispose(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("ClangdLspManager disposing")),this.proxy){try{await this.proxy.dispose()}catch(t){f.warn(`[ClangdLspManager] proxy dispose error: ${t}`)}this.proxy=null}this.isInitialized=!1,this.initPromise=null}getLogPath(){try{let e=Ti.join($t(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=Ti.join(e,"lsp-log",t);return ml.mkdirSync(r,{recursive:!0}),ae(r)}catch{return"auto"}}};function Nm(n){let e=wo(n);return f.info(`[SyncGuard] ${e.reason}`),e}var yl=(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))(yl||{}),Lm=(s=>(s[s.IDLE_CPP=0]="IDLE_CPP",s[s.DISCOVERING_CPP=1]="DISCOVERING_CPP",s[s.SYNCING_CPP=2]="SYNCING_CPP",s[s.INITIALIZING_CPP=3]="INITIALIZING_CPP",s[s.READY_CPP=4]="READY_CPP",s[s.ERROR_CPP=5]="ERROR_CPP",s))(Lm||{}),ht=3,hl=600*1e3,gl=100,Ks=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";sdkPath="";arktsLangServerPath=null;initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e={}){this.config=e,Cn(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),h.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",h.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,h.info(`Constructor: using configured path as startPath: '${t}'`));let i=vt(t);h.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0;let o=Po(this.config.devecoPath);this.sdkPath=o.sdkPath,this.arktsLangServerPath=o.arktsLangServerPath,h.info(`Constructor: sdkPath='${this.sdkPath}', arktsLangServerPath='${this.arktsLangServerPath??"(null)"}'`),this.server=new dC({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=cl(),this.standardProtocolAvailable=this.detectStandardProtocolAvailable(),this.registerTools()}registerTools(){this.registerCheckTool(),this.registerLspFeatureTools(),this.registerRestartTool()}registerRestartTool(){this.toolRouter.add({name:"restart",description:"Restart the MCP server in-place: re-sync the project and re-initialize the LSP, without dropping the client connection. Use to recover from a stuck/ERROR state after fixing the root cause, instead of exiting and reopening the agent. Use target to restart one side only (arkts/cpp) or both (all, default). Caution: if initialization fails again after a restart, the cause is likely a persistent project/SDK configuration issue\u2014do not call restart repeatedly; ask the user to fix the project first.",inputSchema:oe.object({target:oe.enum(["arkts","cpp","all"]).default("all").describe('Which backend to restart: "arkts" (ArkTS ace-server), "cpp" (C++ clangd), or "all" (both, default).')})},async e=>this.handleRestartCall(e))}registerCheckTool(){this.toolRouter.add({name:"check",description:"Perform static syntax analysis on HarmonyOS project source files and return structured diagnostics. Supported languages: ArkTS and C/C++.",inputSchema:oe.object({files:oe.array(oe.string()).min(1).describe("List of source file paths to check, relative to the project root (absolute paths within the project are also accepted). Supports ArkTS and C/C++ files in the same call.")})},async e=>this.handleCheckCall(e))}registerLspFeatureTools(){if(!this.standardProtocolAvailable){h.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=oe.object({file:oe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets (ArkTS) and C/C++ extensions."),line:oe.number().describe("Line number (0-based)"),character:oe.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:i}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async o=>this.handleLspFeatureCall(i,o));this.registerSymbolTools(),this.registerCallHierarchyTool()}getPositionFeatures(){return[{name:"hover",description:"Get hover information (type info, documentation) at a specific position in an ArkTS (.ets) or C/C++ file.",feature:"hover"},{name:"definition",description:"Find where the symbol at the given position is defined. Returns file path, line, and character.",feature:"definition"},{name:"declaration",description:"Find the declaration of the symbol at the given position. In ArkTS, this may differ from definition.",feature:"declaration"},{name:"references",description:"Find all references to the symbol at the given position across the HarmonyOS project.",feature:"references"},{name:"implementation",description:"Find implementations of the symbol at the given position (e.g., interface implementations).",feature:"implementation"}]}registerSymbolTools(){this.toolRouter.add({name:"workspaceSymbol",description:"Search for symbols by name across the entire HarmonyOS project.",inputSchema:oe.object({query:oe.string().describe("Symbol name (or partial) to search for")})},async e=>this.handleWorkspaceSymbolCall(e)),this.toolRouter.add({name:"documentSymbol",description:"Get the symbol tree (functions, classes, variables with ranges) of an ArkTS (.ets) or C/C++ file. Useful for file overview, structured code breakdown, and large file slicing.",inputSchema:oe.object({file:oe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions.")})},async e=>this.handleDocumentSymbolCall(e))}registerCallHierarchyTool(){this.toolRouter.add({name:"callHierarchy",description:'Query call hierarchy for a function at the given position. Use direction "incoming" to find callers, "outgoing" to find callees. ArkTS supports both directions; C/C++ (clangd) supports incoming only.',inputSchema:oe.object({file:oe.string().describe("Source file path, relative to the project root (absolute paths within the project are also accepted). Supports .ets and C/C++ extensions."),line:oe.number().describe("Line number (0-based)"),character:oe.number().describe("Character offset in the line (0-based)"),direction:oe.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.arktsLangServerPath;if(!e)return h.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=Co(e);return h.info(`ArktsCheck protocol: ${t?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${t})`),t}catch(e){return h.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=v.isPathContainedWithSymlink(o,t);s.contained||(h.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
|
|
1287
|
+
`)}],isError:!0}:null}let r=e.filter(i=>Xs.isAbsolute(i));return r.length>0?(h.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(i=>`Absolute path is not allowed: ${i}`).join(`
|
|
1288
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(g=>typeof g=="string"):[];if(t.length===0)return h.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>gl)return h.warn(`check tool called with ${t.length} files (max: ${gl})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${gl}.`}],isError:!0};let r=this.validateContainment(t);if(r)return r;let{etsFiles:i,cppFiles:o,unsupported:s}=pC(t);s.length>0&&h.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(g=>`Unsupported file type: ${g} (only .ets and C/C++ source/header files are supported)`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let l=a.length>0;return{content:[{type:"text",text:[c.join(`
|
|
1289
1289
|
`),a.join(`
|
|
1290
1290
|
`)].filter(g=>g.trim().length>0).join(`
|
|
1291
|
-
`).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${gl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let a=e;return this.cppLspTool.handleLspFeature(a,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${gt})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${gt})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${gl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],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"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=gt?(h.error(`Init retry limit reached (${this.initRetryCount}/${gt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${gt}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${gt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${km[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):bn(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=gt?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${gt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${gt}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${gt})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1292
|
-
`);i&&(e.isError?t.push(i):r.push(i))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~10 seconds.`}]}}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new tC;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=gu();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=St(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?St(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=St(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{h.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new br(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Rm(e),r=!t.required;return h.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await Er.handleSyncProject(e,this.sdkPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=ml?(h.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${ml/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=In(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new xi({workspaceRoot:e,sdkPath:this.sdkPath});try{await this.cppLspManager.start(),this.cppCheckTool=new Cr(this.cppLspManager),this.cppLspTool=new Ir(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await xi.handleSyncCppProject(e,this.sdkPath);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(r/1e3);return r>=ml?(h.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),hu(),mu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function nC(n){let e=[],t=[],r=[];for(let i of n)Ks.extname(i).toLowerCase()===".ets"?e.push(i):bn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function yl(n={}){return new Js(n)}import*as wl from"fs";import*as Li from"path";import{spawn as rC}from"child_process";async function Tm(n){Cn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await iC(n),s=aC(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),lC(s)}async function iC(n){let e=await I.new(),t=e.sourceType==="clt"?e.toolchainRoot:e.devecoStudioPath,r;if(n.projectPath)r=ae(Li.resolve(n.projectPath)),h.info(`projectPath=specified ('${r}'), no search`);else if(n.autoDetect){let l=Eo(process.cwd());r=ae(l??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${l??"null, fallback to cwd"}`)}else r=ae(process.cwd()),h.info(`projectPath=cwd ('${r}'), no search (pass --auto-detect to search subdirs)`);let{sdkPath:i,arktsLangServerPath:o}=bo(t);o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let s=zr(o,!0),a=Li.join(Ut(),"lsp-server",String(Date.now()));wl.mkdirSync(a,{recursive:!0});let c=oC(r,i);return h.info(`projectPath=${r}, sdkPath=${i}, arktsLangServerPath=${o}, serverPath=${s}, logPath=${a}, serverMaxSize=${c}MB`),{projectPath:r,sdkPath:i,serverPath:s,logPath:a,serverMaxSize:c}}function oC(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=sC(n,e),s=xo(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function sC(n,e){try{let t=[];return new Mn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Et(n).getAllModuleInfo().length}catch{return 0}}function aC(n,e,t,r,i){let o=Li.join(e,"lspLog");wl.mkdirSync(o,{recursive:!0});let s=cC(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),rC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function cC(n,e,t,r,i){let o=U(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${U(t)}`,`--sdkPath=${U(r)}`]}function lC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as xm from"fs";import*as Fn from"path";import{spawn as dC}from"child_process";async function Lm(n){Cn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await uC(n),i=Fn.join(t,"compile_commands.json");xm.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=fC(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),hC(o)}async function uC(n){let e=await pC();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=ae(Fn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=Eo(process.cwd());t=ae(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ae(Fn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=Ja(e),i=Co(r);i||(h.error(`clangd not found under sdk '${r}'. Expected at <sdkPath>/default/openharmony/native/llvm/bin/clangd`),process.exit(1));let o=qr(t),s=Fn.dirname(o);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}function pC(){return I.new().then(n=>n.devecoStudioPath).catch(()=>Ka())}function fC(n,e,t){let r=mC(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),dC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function mC(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function hC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function yC(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=n,i=await I.new(),o=i.sourceType==="clt"?i.toolchainRoot:i.devecoStudioPath??null,s=yl({projectPath:r,devecoPath:o??void 0,nodeMaxOldSpaceSize:e,debug:t}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c instanceof Error?c.message:String(c)),process.exit(1)}}var vl=new gC("serve").description("Host bundled auxiliary protocol servers");vl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await yC()});vl.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await Tm({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await Lm({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Nm=vl;import{Command as mA,InvalidArgumentError as rd}from"commander";import{red as pa,dim as hA}from"colorette";var xt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],nn={"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"};import*as Ki from"fs";import nA from"proper-lockfile";import Qh from"ora";import*as rt from"fs";import*as Hi from"path";var Dr="1.9.1",wC=48*1024*1024;var Rr=200,Om=12,Mm=4,Sl=8,_m=6;var Fm=1320,jm=120,Hm=450,$m=250,Um=500,Bm=480,Wm=80,Gm=200,Vm=60,zm=200;var qm=200,Ym=40,El=500,vC=Object.fromEntries(xt.map((n,e)=>[nn[n],e])),rn=Object.fromEntries(xt.map((n,e)=>[n,e]));import*as Ni from"fs";import*as B from"path";import{fileURLToPath as Jm}from"url";var SC="docs";function bl(){return B.join(ut(),SC)}function ge(){return B.join(bl(),".index")}function Xs(){return B.join(ge(),"build.lock")}function Oi(){return B.join(ge(),"build-status.json")}function kr(){return B.join(ge(),"build-meta.json")}function on(){return B.join(ge(),"search.db")}function Tr(){return B.join(ge(),".tmp")}function EC(n,e){let t=e;for(;!t.endsWith(`${B.sep}dist`)&&t!==B.dirname(t);)t=B.dirname(t);return t}function Km(n,e){return B.dirname(EC(n,e))}function Xm(){let n=Jm(import.meta.url),e=B.dirname(n);return n.includes(`${B.sep}dist${B.sep}`)?Km(n,e):B.join(e,"..","..","..")}function bC(...n){let e=Jm(import.meta.url),t=B.dirname(e);return e.includes(`${B.sep}dist${B.sep}`)?[B.join(Km(e,t),...n)]:[B.join(t,"..","..","..",...n)]}function Zm(...n){let e=Xm(),t=Ni.realpathSync(e);for(let r of bC(...n))try{let i=Ni.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=Ni.realpathSync(r);if(!Ua(o,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return o}catch(i){if(i.code!=="ENOENT")throw i}return null}function sn(){return Zm("docs.zip")}function Pl(){return Zm("index.zip")}function Qm(){return B.join(Xm(),"index","data")}import*as jn from"fs";import*as Mi from"path";var Lt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Cl=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var eh=null;function PC(){if(eh)return eh;let n=ge();if(Lt.every(i=>jn.existsSync(Mi.join(n,i))))return n;let t=Qm();if(Lt.every(i=>jn.existsSync(Mi.join(t,i))))return t;throw new Cl("Lexicon files not found. Install the documentation index first (index.zip).")}function xr(n){let e=Mi.join(PC(),n);return jn.readFileSync(e,"utf-8")}function th(n,e){return jn.readFileSync(Mi.join(e,n),"utf-8")}import*as Zs from"fs";import*as nh from"path";import*as rh from"yauzl";var _i=null;function CC(n){return new Promise((e,t)=>{rh.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function IC(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function AC(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=IC(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function DC(){_i?.zipfile.close(),_i=null}async function RC(n){let e=nh.resolve(n),t=await Zs.promises.stat(e),r=_i;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;DC();let i=await CC(e),o=await AC(i);return _i={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},_i}function kC(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function TC(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await kC(n.zipfile,e)}finally{r()}}function xC(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function LC(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Il(n){let e=sn();if(!e)throw new Error("docs.zip not found");let t=await RC(e),r=LC(t.entries,xC(n));if(!r)throw new Error(`Document not found: ${n}`);return(await TC(t,r)).toString("utf-8")}function Al(){let n=sn();return n!==null&&Zs.existsSync(n)}import*as Pe from"fs";import*as an from"path";import ih from"adm-zip";import*as Fi from"fs";import*as ea from"path";var Qs=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Lr(n){return n instanceof kn||n instanceof Qs||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function kl(n){return new Qs(n)}function NC(){return ct(ut())}function Rl(n,e,t){let r=uo(n,e);if(r===null)throw kl(`${t} resolves outside the data directory.`);return r}async function Dl(n,e){await Fi.promises.mkdir(n,{recursive:!0});let t=Rl(n,e,"directory");if(!(await Fi.promises.stat(t)).isDirectory())throw kl("path must be a directory.")}function OC(n){let e=NC();try{let t=Rl(n,e,"file");if(!Fi.statSync(t).isFile())throw kl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){Rl(ea.dirname(n),e,"file parent");return}throw t}}async function Nr(n={}){let e=n.mode??"write",t=await ip();await Dl(bl(),t),await Dl(ge(),t),e==="write"&&await Dl(Tr(),t);for(let r of[on(),kr(),Oi(),Xs(),...Lt.map(i=>ea.join(ge(),i))])OC(r)}var Tl=["search.db","build-meta.json",...Lt],MC=["corpus.json","corpus-offsets.json","orama.dpack"];async function _C(n){for(let e of MC)await Pe.promises.rm(an.join(n,e),{force:!0})}function oh(n){let t=new ih(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 FC(n){let e=ge();await Pe.promises.mkdir(e,{recursive:!0});for(let t of Tl){let r=an.join(e,t);await Pe.promises.rm(r,{force:!0}),await Pe.promises.rename(an.join(n,t),r)}await _C(e),await Pe.promises.rm(Tr(),{recursive:!0,force:!0})}function sh(n){let e=Pl();if(!e)return!1;try{let t=oh(e);return t.indexVersion===Dr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function ah(n){await Nr({mode:"write"});let e=Pl();if(!e)throw new Error("index.zip not found");let t=oh(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=Tr();await Pe.promises.rm(r,{recursive:!0,force:!0}),await Pe.promises.mkdir(r,{recursive:!0});let i=new ih(e);for(let s of Tl){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Pe.promises.writeFile(an.join(r,s),a.getData())}let o=JSON.parse(await Pe.promises.readFile(an.join(r,"build-meta.json"),"utf-8"));if(!Pe.existsSync(an.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await FC(r),o}async function ch(){await Pe.promises.rm(Tr(),{recursive:!0,force:!0});let n=ge();for(let e of Tl)await Pe.promises.rm(an.join(n,e),{force:!0})}import{createHash as lh}from"crypto";import*as dh from"fs";async function ji(n){return new Promise((e,t)=>{let r=lh("sha256"),i=dh.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function uh(n){return lh("sha256").update(n,"utf8").digest("hex")}var xl=null;function jC(){let n=xr("harmonyos-synonyms.json");return JSON.parse(n)}function HC(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function $C(){let n=HC(jC()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function UC(){return xl||(xl=$C()),xl}function Ll(n,e){let t=UC(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function ph(n,e){let t=e?th(n,e):xr(n);return uh(t)}function Nl(n){return ph("harmonyos-synonyms.json",n)}function Ol(n){return ph("harmonyos-terms.txt",n)}var BC={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ta(){try{let n=await rt.promises.readFile(Oi(),"utf-8");return JSON.parse(n)}catch{return{...BC}}}async function Ml(n){let e=Oi();await rt.promises.mkdir(Hi.dirname(e),{recursive:!0}),await rt.promises.writeFile(e,JSON.stringify(n,null,2))}function fh(n){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function $i(n){let t={...await ta(),...n,updatedAt:Date.now()};return await Ml(t),t}async function _l(){let n=sn();return n?ji(n):null}async function Fl(){try{let n=await rt.promises.readFile(kr(),"utf-8");return JSON.parse(n)}catch{return null}}async function na(n=!1){if(n)return"no-index";let e=await Fl();if(!e||e.segmentCount===0)return"no-index";let t=await _l();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Dr?"engine-upgraded":e.termsHash!==Ol()?"terms-changed":e.synonymsHash!==Nl()?"synonyms-changed":null}function Ui(){if(!Al()||!rt.existsSync(on())||!rt.existsSync(kr()))return!1;let n=Hi.dirname(on());if(!Lt.every(e=>rt.existsSync(Hi.join(n,e))))return!1;try{let e=rt.readFileSync(kr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function jl(n=!1){return n?!0:Al()?Ui()?await na()!==null:!0:!1}async function mh(){let n=await ta();return["installing","indexing","persisting"].includes(n.state)}var hh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),Hl=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),gh=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"]),yh=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 WC=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,GC=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,VC=/[A-Z][a-zA-Z0-9]{2,}/g,zC=/@[A-Z][a-zA-Z0-9]*/g,qC=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,wh=6,YC=/^[a-z][a-z0-9]{2,}$/,JC=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,KC=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,XC=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,ZC=/^[A-Z][a-zA-Z0-9]+$/;function QC(n){return`"${n.replace(/"/g,'""')}"`}function Wi(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(QC).join(` ${e} `)}function Bi(n){return Wi(n,"OR")}function vh(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Bi([...t,...r]):`(${Bi(t)}) AND (${Bi(r)})`}function Gi(n){return KC.test(n)}function Sh(n){return XC.test(n)&&n.length>=wh}function eI(n){return ZC.test(n)}function Vi(n){return Gi(n)||Sh(n)||eI(n)}function tI(n){let e=n.trim().toLowerCase();return yh.has(e)?!1:hh.has(e)}function nI(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function $l(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Eh(n){return[...n.matchAll(WC)].map(e=>e[0])}function bh(n,e=wh){let t=[];for(let r of n.matchAll(GC))r[0].length>=e&&t.push(r[0]);return t}function zi(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function cn(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function rI(n){let e=new Set;cn(e,n);let t=$l(n);return t&&cn(e,t),zi([...e])}function ra(n){if(Gi(n))return rI(n);let e=new Set;return cn(e,n),zi([...e])}function ia(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(JC);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!YC.test(r)||gh.has(r)||!tI(i))return null;let o=nI(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function Ul(n){let e=ia(n.trim());return!e||e.second!=="manager"?null:e}function iI(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Ph(n){let e=n.trim(),t=Ul(e);if(t&&Hl.has(t.first))return!0;if(Sh(e)){let r=iI(e);return r!==null&&Hl.has(r)}return!1}function Bl(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function Wl(n){let e=n.trim();if(Vi(e))return ra(e);let t=new Set;for(let r of Eh(n)){cn(t,r);let i=$l(r);i&&cn(t,i)}for(let r of bh(n))cn(t,r);for(let r of n.matchAll(zC))t.add(r[0]);for(let r of n.matchAll(qC))t.add(r[0]);for(let r of n.matchAll(VC))r[0].length>=4&&t.add(r[0]);return zi([...t])}function Ch(n){let e=n.trim();if(Vi(e))return ra(e);let t=new Set,r=ia(e);r&&cn(t,r.camelCase);for(let i of Wl(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return zi([...t])}function Ih(n){return Vi(n)}var Y={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 Ah(n){return Y.pureApiSymbol.test(n.trim())}function qi(n){let e=n.trim();return Y.stageModelExact.test(e)||Y.stageModelEnglishExact.test(e)}function Dh(n){let e=[];return qi(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),Y.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),Y.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 Rh(n){return qi(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var oI=[{matches:n=>Y.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>qi(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!qi(n)&&Y.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>Y.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>Y.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>Y.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>Y.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>Y.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=>Y.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function sI(n,e){for(let{catalog:t,multiplier:r}of e){let i=rn[t];n.set(i,(n.get(i)??1)*r)}}function kh(n,e){for(let t of oI)t.matches(n)&&sI(e,t.weights)}function Th(n,e){if(e!==void 0)return!1;let t=n.trim();return Gi(t)||Y.pureApiSymbol.test(t)||Ph(t)}function xh(n){let e=n.trim();if(Gi(e)||Y.pureApiSymbol.test(e))return"harmonyos-references";if(qi(e)||Y.uiAbilityLifecycleCatalog.test(e)||Y.stateDecoratorCatalog.test(e)||Y.stateManagement.test(e)||Y.declarePermissionCatalog.test(e)||Y.stageModelEntryPage.test(e)||Y.routerRoute.test(e)||Y.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as aI}from"module";var cI=aI(import.meta.url),oa=null,Gl=null,Vl=null;function lI(){if(oa)return oa;let n=xr("harmonyos-stopwords.txt");return oa=new Set(n.split(`
|
|
1293
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
1291
|
+
`).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${yl[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return h.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:i,character:o});let a=e;return this.cppLspTool.handleLspFeature(a,{file:r,line:i,character:o})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return h.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let i=[],o=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),o,i)}catch(a){h.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:i.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(i,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",i=t?.location?.range?.start?.line??0,o=t?.location?.range?.start?.character??0;return`${r}:${i}:${o}`}mergeSymbolItems(e,t,r){if(e)for(let i of e){let o=this.symbolDedupKey(i);t.has(o)||(t.add(o),r.push(i))}}describeArktsState(){switch(this.projectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 10s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.initRetryCount}/${ht})`;case 4:return"ready";default:return"unknown"}}describeCppState(){switch(this.cppProjectState){case 0:return"idle";case 1:return"discovering";case 2:return"syncing (retry 25s)";case 3:return"initializing (retry 10s)";case 5:return`error (${this.cppInitRetryCount}/${ht})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeLspRequest(t,"documentSymbol",async()=>t.endsWith(".ets")?this.arktsCheckTool.handleDocumentSymbol(t):this.cppLspTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeLspRequest(t,`callHierarchy(${o})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${yl[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return h.warn(`ArkTS ${e} rejected: unknown project state ${this.projectState}`),{content:[{type:"text",text:"Unknown project state, please retry"}],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"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=ht?(h.error(`Init retry limit reached (${this.initRetryCount}/${ht}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${ht}). Ask the user to investigate and confirm \`ohpm install\` + \`hvigor\` sync succeed manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${ht})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return h.warn(`C++ ${e} rejected: C++ project is ${Lm[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return h.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return h.warn(`C++ ${e} rejected: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:"Unknown C++ project state, please retry"}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):bn(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",h.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=ht?(h.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${ht}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${ht}). Ask the user to investigate and confirm \`hvigor compileNative\` succeeds manually. Do NOT call the \`restart\` tool repeatedly \u2014 call it at most once after the user fixes the root cause; if it fails again, stop retrying and escalate to the user.`}],isError:!0}):(h.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${ht})`),this.ensureCppProjectReady(),{content:[{type:"text",text:"C++ project initialization failed, auto-retrying, please retry in 25 seconds"}],isError:!0})}async callCppCheck(e){return this.routeCppRequest("check",async()=>this.cppCheckTool.handleCall({files:e}))}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1292
|
+
`);i&&(e.isError?t.push(i):r.push(i))}async handleRestartCall(e){let t=e.target,r=t==="cpp"?"cpp":t==="arkts"?"arkts":"all";return this.restartProject(r),{content:[{type:"text",text:`MCP server is restarting in-place (${r==="all"?"ArkTS + C++":r==="cpp"?"C++":"ArkTS"}): re-sync project + re-initialize LSP. Client connection preserved\u2014no need to exit the agent. Please retry tools in ~10 seconds.`}]}}restartProject(e){h.info(`[restart] resetting tools + state, re-init (target=${e})`),(e==="arkts"||e==="all")&&this.restartArkts(),(e==="cpp"||e==="all")&&this.restartCpp()}restartArkts(){this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(e=>h.warn("Failed to shutdown ArktsCheckTool during restart:",e)),this.arktsCheckTool=null),this.initRetryCount=0,this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.configChangedTriggeredResync=!1,this.initPromise?(this.needsReinit=!0,h.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>h.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>h.warn("Failed to dispose ClangdLspManager during restart:",e)),this.cppLspManager=null),this.cppInitRetryCount=0,this.cppHasNoCppCode=!1,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>h.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{h.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,h.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{h.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new uC;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=yu();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=vt(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?vt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=vt(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{h.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new br(this.config.projectPath,this.sdkPath,this.arktsLangServerPath,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Nm(e),r=!t.required;return h.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,h.info("Starting project sync...");let r=await Er.handleSyncProject(e,this.sdkPath,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let i=Date.now()-this.syncSkipStartedAt,o=Math.round(i/1e3);return i>=hl?(h.error(`Sync skipped for ${o}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${o}s / ${hl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return h.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{h.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){h.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=In(e);if(t.length===0){h.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,h.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new xi({workspaceRoot:e,sdkPath:this.sdkPath});try{await this.cppLspManager.start(),this.cppCheckTool=new Cr(this.cppLspManager),this.cppLspTool=new Ir(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,h.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){h.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,h.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await xi.handleSyncCppProject(e,this.sdkPath);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,i=Math.round(r/1e3);return r>=hl?(h.error(`[Cpp] C++ sync skipped for ${i}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(h.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${i}s)`),this.cppProjectState=0,!1)}case"failed":return h.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),gu(),hu()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function pC(n){let e=[],t=[],r=[];for(let i of n)Xs.extname(i).toLowerCase()===".ets"?e.push(i):bn(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function wl(n={}){return new Ks(n)}import*as vl from"fs";import*as Ni from"path";import{spawn as fC}from"child_process";async function Om(n){Cn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await mC(n),s=yC(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),vC(s)}async function mC(n){let e=await A.new(),t=e.sourceType==="clt"?e.toolchainRoot:e.devecoStudioPath,r;if(n.projectPath)r=ae(Ni.resolve(n.projectPath)),h.info(`projectPath=specified ('${r}'), no search`);else if(n.autoDetect){let l=Eo(process.cwd());r=ae(l??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${l??"null, fallback to cwd"}`)}else r=ae(process.cwd()),h.info(`projectPath=cwd ('${r}'), no search (pass --auto-detect to search subdirs)`);let{sdkPath:i,arktsLangServerPath:o}=Po(t);o||(h.error("ace-server not found (install DevEco Studio / CLT)."),process.exit(1));let s=zr(o,!0),a=Ni.join($t(),"lsp-server",String(Date.now()));vl.mkdirSync(a,{recursive:!0});let c=hC(r,i);return h.info(`projectPath=${r}, sdkPath=${i}, arktsLangServerPath=${o}, serverPath=${s}, logPath=${a}, serverMaxSize=${c}MB`),{projectPath:r,sdkPath:i,serverPath:s,logPath:a,serverMaxSize:c}}function hC(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=gC(n,e),s=No(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function gC(n,e){try{let t=[];return new Mn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new St(n).getAllModuleInfo().length}catch{return 0}}function yC(n,e,t,r,i){let o=Ni.join(e,"lspLog");vl.mkdirSync(o,{recursive:!0});let s=wC(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),fC(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function wC(n,e,t,r,i){let o=U(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${U(t)}`,`--sdkPath=${U(r)}`]}function vC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as Mm from"fs";import*as Fn from"path";import{spawn as SC}from"child_process";async function _m(n){Cn(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await EC(n),i=Fn.join(t,"compile_commands.json");Mm.existsSync(i)||h.warn(`compile_commands.json not found at ${i}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let o=PC(e,t,r);h.info("clangd started, bridging stdio (initialize is left to the client)"),IC(o)}async function EC(n){let e=await bC();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t;if(n.projectPath)t=ae(Fn.resolve(n.projectPath)),h.info(`projectPath=specified ('${t}'), no search`);else if(n.autoDetect){let a=Eo(process.cwd());t=ae(a??process.cwd()),h.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else t=ae(Fn.resolve(process.cwd())),h.info(`projectPath=cwd ('${t}'), no search (pass --auto-detect to search subdirs)`);let r=Ka(e),i=Io(r);i||(h.error(`clangd not found under sdk '${r}'. Expected at <sdkPath>/default/openharmony/native/llvm/bin/clangd`),process.exit(1));let o=qr(t),s=Fn.dirname(o);return h.info(`projectPath=${t}, sdkPath=${r}, clangdPath=${i}, compileCommandsDir=${s}`),{projectPath:t,clangdPath:i,compileCommandsDir:s}}function bC(){return A.new().then(n=>n.devecoStudioPath).catch(()=>Xa())}function PC(n,e,t){let r=CC(e);return h.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),SC(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function CC(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function IC(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function DC(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=n,i=await A.new(),o=i.sourceType==="clt"?i.toolchainRoot:i.devecoStudioPath??null,s=wl({projectPath:r,devecoPath:o??void 0,nodeMaxOldSpaceSize:e,debug:t}),a=async()=>{await s.shutdown(),process.exit(0)};process.once("SIGINT",a),process.once("SIGTERM",a),process.platform==="win32"&&process.once("SIGBREAK",a);try{await s.start()}catch(c){console.error("Failed to start MCP server:",c instanceof Error?c.message:String(c)),process.exit(1)}}var Sl=new AC("serve").description("Host bundled auxiliary protocol servers");Sl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await DC()});Sl.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--cpp","Start the C/C++ language server (clangd)").option("--project-path <path>","project root path (used as-is, no search)").option("--auto-detect","When --project-path is not specified, search the current directory and its subdirectories for the project root (no upward search)").action(async n=>{n.arkts&&n.cpp&&(console.error("--arkts and --cpp are mutually exclusive. Specify only one."),process.exit(1)),n.arkts?await Om({projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await _m({projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var Fm=Sl;import{Command as CA,InvalidArgumentError as id}from"commander";import{red as fa,dim as IA}from"colorette";var Tt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],nn={"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"};import*as Ki from"fs";import pA from"proper-lockfile";import rg from"ora";import*as rt from"fs";import*as Hi from"path";var Dr="1.9.1",RC=48*1024*1024;var Rr=200,jm=12,Hm=4,El=8,$m=6;var Um=1320,Bm=120,Wm=450,Gm=250,Vm=500,zm=480,qm=80,Ym=200,Jm=60,Km=200;var Xm=200,Zm=40,bl=500,kC=Object.fromEntries(Tt.map((n,e)=>[nn[n],e])),rn=Object.fromEntries(Tt.map((n,e)=>[n,e]));import*as Li from"fs";import*as B from"path";import{fileURLToPath as Qm}from"url";var TC="docs";function Pl(){return B.join(ut(),TC)}function ge(){return B.join(Pl(),".index")}function Zs(){return B.join(ge(),"build.lock")}function Oi(){return B.join(ge(),"build-status.json")}function kr(){return B.join(ge(),"build-meta.json")}function on(){return B.join(ge(),"search.db")}function Tr(){return B.join(ge(),".tmp")}function xC(n,e){let t=e;for(;!t.endsWith(`${B.sep}dist`)&&t!==B.dirname(t);)t=B.dirname(t);return t}function eh(n,e){return B.dirname(xC(n,e))}function th(){let n=Qm(import.meta.url),e=B.dirname(n);return n.includes(`${B.sep}dist${B.sep}`)?eh(n,e):B.join(e,"..","..","..")}function NC(...n){let e=Qm(import.meta.url),t=B.dirname(e);return e.includes(`${B.sep}dist${B.sep}`)?[B.join(eh(e,t),...n)]:[B.join(t,"..","..","..",...n)]}function nh(...n){let e=th(),t=Li.realpathSync(e);for(let r of NC(...n))try{let i=Li.lstatSync(r);if(i.isSymbolicLink()||!i.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let o=Li.realpathSync(r);if(!Ba(o,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return o}catch(i){if(i.code!=="ENOENT")throw i}return null}function sn(){return nh("docs.zip")}function Cl(){return nh("index.zip")}function rh(){return B.join(th(),"index","data")}import*as jn from"fs";import*as Mi from"path";var xt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Il=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var ih=null;function LC(){if(ih)return ih;let n=ge();if(xt.every(i=>jn.existsSync(Mi.join(n,i))))return n;let t=rh();if(xt.every(i=>jn.existsSync(Mi.join(t,i))))return t;throw new Il("Lexicon files not found. Install the documentation index first (index.zip).")}function xr(n){let e=Mi.join(LC(),n);return jn.readFileSync(e,"utf-8")}function oh(n,e){return jn.readFileSync(Mi.join(e,n),"utf-8")}import*as Qs from"fs";import*as sh from"path";import*as ah from"yauzl";var _i=null;function OC(n){return new Promise((e,t)=>{ah.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function MC(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function _C(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=MC(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function FC(){_i?.zipfile.close(),_i=null}async function jC(n){let e=sh.resolve(n),t=await Qs.promises.stat(e),r=_i;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;FC();let i=await OC(e),o=await _C(i);return _i={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},_i}function HC(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function $C(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await HC(n.zipfile,e)}finally{r()}}function UC(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");if(e.split("/").includes(".."))throw new Error("Invalid document ID: path traversal is not allowed.");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function BC(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Al(n){let e=sn();if(!e)throw new Error("docs.zip not found");let t=await jC(e),r=BC(t.entries,UC(n));if(!r)throw new Error(`Document not found: ${n}`);return(await $C(t,r)).toString("utf-8")}function Dl(){let n=sn();return n!==null&&Qs.existsSync(n)}import*as Ce from"fs";import*as an from"path";import ch from"adm-zip";import*as Fi from"fs";import*as ta from"path";var ea=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function Nr(n){return n instanceof kn||n instanceof ea||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function Tl(n){return new ea(n)}function WC(){return ct(ut())}function kl(n,e,t){let r=uo(n,e);if(r===null)throw Tl(`${t} resolves outside the data directory.`);return r}async function Rl(n,e){await Fi.promises.mkdir(n,{recursive:!0});let t=kl(n,e,"directory");if(!(await Fi.promises.stat(t)).isDirectory())throw Tl("path must be a directory.")}function GC(n){let e=WC();try{let t=kl(n,e,"file");if(!Fi.statSync(t).isFile())throw Tl("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){kl(ta.dirname(n),e,"file parent");return}throw t}}async function Lr(n={}){let e=n.mode??"write",t=await op();await Rl(Pl(),t),await Rl(ge(),t),e==="write"&&await Rl(Tr(),t);for(let r of[on(),kr(),Oi(),Zs(),...xt.map(i=>ta.join(ge(),i))])GC(r)}var xl=["search.db","build-meta.json",...xt],VC=["corpus.json","corpus-offsets.json","orama.dpack"];async function zC(n){for(let e of VC)await Ce.promises.rm(an.join(n,e),{force:!0})}function lh(n){let t=new ch(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 qC(n){let e=ge();await Ce.promises.mkdir(e,{recursive:!0});for(let t of xl){let r=an.join(e,t);await Ce.promises.rm(r,{force:!0}),await Ce.promises.rename(an.join(n,t),r)}await zC(e),await Ce.promises.rm(Tr(),{recursive:!0,force:!0})}function dh(n){let e=Cl();if(!e)return!1;try{let t=lh(e);return t.indexVersion===Dr&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function uh(n){await Lr({mode:"write"});let e=Cl();if(!e)throw new Error("index.zip not found");let t=lh(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=Tr();await Ce.promises.rm(r,{recursive:!0,force:!0}),await Ce.promises.mkdir(r,{recursive:!0});let i=new ch(e);for(let s of xl){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await Ce.promises.writeFile(an.join(r,s),a.getData())}let o=JSON.parse(await Ce.promises.readFile(an.join(r,"build-meta.json"),"utf-8"));if(!Ce.existsSync(an.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await qC(r),o}async function ph(){await Ce.promises.rm(Tr(),{recursive:!0,force:!0});let n=ge();for(let e of xl)await Ce.promises.rm(an.join(n,e),{force:!0})}import{createHash as fh}from"crypto";import*as mh from"fs";async function ji(n){return new Promise((e,t)=>{let r=fh("sha256"),i=mh.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function hh(n){return fh("sha256").update(n,"utf8").digest("hex")}var Nl=null;function YC(){let n=xr("harmonyos-synonyms.json");return JSON.parse(n)}function JC(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function KC(){let n=JC(YC()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function XC(){return Nl||(Nl=KC()),Nl}function Ll(n,e){let t=XC(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function gh(n,e){let t=e?oh(n,e):xr(n);return hh(t)}function Ol(n){return gh("harmonyos-synonyms.json",n)}function Ml(n){return gh("harmonyos-terms.txt",n)}var ZC={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function na(){try{let n=await rt.promises.readFile(Oi(),"utf-8");return JSON.parse(n)}catch{return{...ZC}}}async function _l(n){let e=Oi();await rt.promises.mkdir(Hi.dirname(e),{recursive:!0}),await rt.promises.writeFile(e,JSON.stringify(n,null,2))}function yh(n){let e=Date.now();return{state:"installing",phase:1,phaseLabel:"Preparing documentation index",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function $i(n){let t={...await na(),...n,updatedAt:Date.now()};return await _l(t),t}async function Fl(){let n=sn();return n?ji(n):null}async function jl(){try{let n=await rt.promises.readFile(kr(),"utf-8");return JSON.parse(n)}catch{return null}}async function ra(n=!1){if(n)return"no-index";let e=await jl();if(!e||e.segmentCount===0)return"no-index";let t=await Fl();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Dr?"engine-upgraded":e.termsHash!==Ml()?"terms-changed":e.synonymsHash!==Ol()?"synonyms-changed":null}function Ui(){if(!Dl()||!rt.existsSync(on())||!rt.existsSync(kr()))return!1;let n=Hi.dirname(on());if(!xt.every(e=>rt.existsSync(Hi.join(n,e))))return!1;try{let e=rt.readFileSync(kr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Hl(n=!1){return n?!0:Dl()?Ui()?await ra()!==null:!0:!1}async function wh(){let n=await na();return["installing","indexing","persisting"].includes(n.state)}var vh=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),$l=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Sh=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Eh=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 QC=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,eI=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,tI=/[A-Z][a-zA-Z0-9]{2,}/g,nI=/@[A-Z][a-zA-Z0-9]*/g,rI=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,bh=6,iI=/^[a-z][a-z0-9]{2,}$/,oI=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,sI=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,aI=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,cI=/^[A-Z][a-zA-Z0-9]+$/;function lI(n){return`"${n.replace(/"/g,'""')}"`}function Wi(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(lI).join(` ${e} `)}function Bi(n){return Wi(n,"OR")}function Ph(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Bi([...t,...r]):`(${Bi(t)}) AND (${Bi(r)})`}function Gi(n){return sI.test(n)}function Ch(n){return aI.test(n)&&n.length>=bh}function dI(n){return cI.test(n)}function Vi(n){return Gi(n)||Ch(n)||dI(n)}function uI(n){let e=n.trim().toLowerCase();return Eh.has(e)?!1:vh.has(e)}function pI(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ul(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function Ih(n){return[...n.matchAll(QC)].map(e=>e[0])}function Ah(n,e=bh){let t=[];for(let r of n.matchAll(eI))r[0].length>=e&&t.push(r[0]);return t}function zi(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function cn(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function fI(n){let e=new Set;cn(e,n);let t=Ul(n);return t&&cn(e,t),zi([...e])}function ia(n){if(Gi(n))return fI(n);let e=new Set;return cn(e,n),zi([...e])}function oa(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(oI);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!iI.test(r)||Sh.has(r)||!uI(i))return null;let o=pI(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function Bl(n){let e=oa(n.trim());return!e||e.second!=="manager"?null:e}function mI(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Dh(n){let e=n.trim(),t=Bl(e);if(t&&$l.has(t.first))return!0;if(Ch(e)){let r=mI(e);return r!==null&&$l.has(r)}return!1}function Wl(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function Gl(n){let e=n.trim();if(Vi(e))return ia(e);let t=new Set;for(let r of Ih(n)){cn(t,r);let i=Ul(r);i&&cn(t,i)}for(let r of Ah(n))cn(t,r);for(let r of n.matchAll(nI))t.add(r[0]);for(let r of n.matchAll(rI))t.add(r[0]);for(let r of n.matchAll(tI))r[0].length>=4&&t.add(r[0]);return zi([...t])}function Rh(n){let e=n.trim();if(Vi(e))return ia(e);let t=new Set,r=oa(e);r&&cn(t,r.camelCase);for(let i of Gl(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return zi([...t])}function kh(n){return Vi(n)}var Y={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 Th(n){return Y.pureApiSymbol.test(n.trim())}function qi(n){let e=n.trim();return Y.stageModelExact.test(e)||Y.stageModelEnglishExact.test(e)}function xh(n){let e=[];return qi(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),Y.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),Y.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Nh(n){return qi(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var hI=[{matches:n=>Y.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>qi(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!qi(n)&&Y.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>Y.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>Y.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>Y.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>Y.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>Y.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=>Y.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function gI(n,e){for(let{catalog:t,multiplier:r}of e){let i=rn[t];n.set(i,(n.get(i)??1)*r)}}function Lh(n,e){for(let t of hI)t.matches(n)&&gI(e,t.weights)}function Oh(n,e){if(e!==void 0)return!1;let t=n.trim();return Gi(t)||Y.pureApiSymbol.test(t)||Dh(t)}function Mh(n){let e=n.trim();if(Gi(e)||Y.pureApiSymbol.test(e))return"harmonyos-references";if(qi(e)||Y.uiAbilityLifecycleCatalog.test(e)||Y.stateDecoratorCatalog.test(e)||Y.stateManagement.test(e)||Y.declarePermissionCatalog.test(e)||Y.stageModelEntryPage.test(e)||Y.routerRoute.test(e)||Y.dialogPopupExact.test(e))return"harmonyos-guides"}import{createRequire as yI}from"module";var wI=yI(import.meta.url),sa=null,Vl=null,zl=null;function vI(){if(sa)return sa;let n=xr("harmonyos-stopwords.txt");return sa=new Set(n.split(`
|
|
1293
|
+
`).map(e=>e.trim()).filter(Boolean)),sa}function SI(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function _h(n){let e=vI(),t=[];for(let r of SI(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function EI(){let{cut:n,cut_for_search:e,with_dict:t}=wI("jieba-wasm"),r=xr("harmonyos-terms.txt");return t(r),m("doc-index: using jieba-wasm backend"),{cut:(i,o)=>n(i,o),cutForSearch:(i,o)=>e(i,o)}}async function Yi(){return Vl||(zl||(zl=EI().then(n=>(Vl=n,n))),zl)}async function bI(n){let e=await Yi();return _h(e.cutForSearch(n,!0))}async function Fh(n){let e=await Yi();return _h(e.cut(n,!0))}async function aa(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await bI(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function PI(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function jh(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?zm:Um,i=e?Ym:Wm,o=e?await PI(n.apiSymbols,i):await aa(n.apiSymbols.join(" "),i),a=(await Promise.all([aa(t,e?qm:Bm),Promise.resolve(o),aa(n.headingsText,e?Jm:Gm),aa(n.bodySample,e?Km:Vm)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function CI(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Rr)}function ql(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=jm))break}return r}function II(n){return n.length>=2&&n.length<=Hm}function AI(n,e){let t=Ll(n,El),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=ql(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Ph(i,o)}}function DI(n,e){let t=ql(ia(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Bi(t)}}async function Hh(n){let e=CI(n),t=e.trim(),r=Nh(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=oa(t);if(i)return AI(e,i);if(Vi(t))return DI(e,t);let o=xh(e),s=[...Gl(e),...o],c=kh(t)?e:Ll(e,El),l=await Fh(c),d=ql(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:o.length===0&&II(d)}}var $h=["harmonyos-releases","harmonyos-roadmap"],RI=new Set($h.map(n=>rn[n])),kI=$h.map(n=>`${nn[n]}/`);function TI(n){return RI.has(n)}function xI(n){return kI.some(e=>n.startsWith(e))}function Uh(n){let e=[],t=[];for(let r of n)TI(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Bh(n){let e=[],t=[];for(let r of n)xI(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var NI=[{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 Ji(n,e,t){let r=rn[e];n.set(r,(n.get(r)??1)*t)}function LI(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){Ji(e,"harmonyos-guides",1.45),Ji(e,"harmonyos-references",1.35);return}(i||o)&&Ji(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&Ji(e,"harmonyos-references",1.75)}function Wh(n){let e=new Map,t=n.trim();if(!t)return e;let r=Th(t);LI(t,e),Lh(t,e);for(let i of NI)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||Ji(e,i.catalog,i.multiplier));return e}function Gh(n){return Mh(n)}import{readFile as eA,stat as tA,writeFile as nA}from"fs/promises";var OI=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function MI(n,e){let t=-1;for(let r of OI){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function Vh(n,e,t={}){let{maxLen:r=Xm,contextChars:i=Zm,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(yt=>yt.trim()).filter(Boolean),c=0;for(let yt of a){let at=s.toLowerCase().indexOf(yt.toLowerCase());if(at>=0){c=at;break}}let l=Math.max(0,c-i),d=Math.min(s.length,l+r),g=s.slice(l,d),w=MI(g,r-25);w>=0&&(d=l+w);let P=s.slice(l,d).trim(),O=l>0?"...":"",te=d<s.length||o?"...":"";return`${O}${P}${te}`}var _I=`
|
|
1294
1294
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1295
1295
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1296
1296
|
FROM segments_fts
|
|
@@ -1299,7 +1299,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1299
1299
|
WHERE segments_fts MATCH ?
|
|
1300
1300
|
ORDER BY bm25(segments_fts)
|
|
1301
1301
|
LIMIT ?
|
|
1302
|
-
`,
|
|
1302
|
+
`,FI=`
|
|
1303
1303
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1304
1304
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
1305
1305
|
FROM segments_fts
|
|
@@ -1308,7 +1308,7 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1308
1308
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
1309
1309
|
ORDER BY bm25(segments_fts)
|
|
1310
1310
|
LIMIT ?
|
|
1311
|
-
`,
|
|
1311
|
+
`,jI=3.5,HI=1.4,$I=4,UI=1.8,BI=1.35,WI=3.5,GI=1.8,VI=120,zh=6;function Jl(n){return n.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function zI(n){return n.split(/[^\p{L}\p{N}@.]+/u).map(Jl).filter(e=>e.length>=2)}function qI(n,e){return e.length>1&&e.every(t=>n.includes(t))}function YI(n){return/^[a-z0-9]{1,4}$/.test(n.trim().toLowerCase())}function JI(n,e){return n===e?WI:n.startsWith(e)||n.includes(`@ohos.${e}`)?GI:1}function KI(n,e){let t=Jl(e);if(t.length<2)return 1;let r=Jl(n.doc_title);if(YI(e))return JI(r,t);if(r.includes(t))return $I;if(t.length>=zh&&r.includes(t.slice(0,zh)))return UI;let i=zI(e);return qI(r,i)?BI:1}function XI(n,e){return e<=1?n:n<0?n*e:n/e}function ca(n,e,t,r){let i=n.bm25/(e.get(n.catalog_id)??1);return i=XI(i,KI(n,t)),r&&Wl(n.doc_title,n.section_title,r)&&(i/=jI,n.catalog_id===rn["harmonyos-references"]&&(i/=HI)),i}function Yl(n,e,t,r){return n.reduce((i,o)=>ca(o,e,t,r)<ca(i,e,t,r)?o:i)}function ZI(n,e){return e.some(t=>n.section_title.includes(t)||n.doc_title.includes(t))}function QI(n,e,t,r,i){if(i){let o=n.filter(s=>Wl(s.doc_title,s.section_title,i));if(o.length>0)return Yl(o,t,r,i)}if(e.length>0){let o=n.filter(s=>ZI(s,e));if(o.length>0)return Yl(o,t,r,i)}return Yl(n,t,r,i)}function qh(n,e,t,r,i){let o=Wh(e),s=Rh(e),c=Bl(e)?.camelCase,l=new Map;for(let P of n){let O=l.get(P.document_id)??[];O.push(P),l.set(P.document_id,O)}let d=[];for(let P of l.values())d.push(QI(P,s,o,t,c));let g=d.sort((P,O)=>ca(P,o,t,c)-ca(O,o,t,c));return(i?Uh(g):g).slice(0,r)}function Yh(n,e,t,r,i,o){let s=e?rn[e]:void 0,a=Math.max(t,t*$m,VI),c=s===void 0?n.all(_I,r,a):n.all(FI,r,s,a);return(s===void 0?qh(c,o,i,t,!0):qh(c,o,i,t,!1)).map(d=>({title:d.doc_title,documentId:d.document_id,sectionTitle:d.section_title||void 0,snippet:Vh(d.lead_text,i,{excerptTruncated:!!d.excerpt_truncated})}))}var Jh=`
|
|
1312
1312
|
CREATE TABLE documents (
|
|
1313
1313
|
id INTEGER PRIMARY KEY,
|
|
1314
1314
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -1346,40 +1346,40 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
1346
1346
|
END;
|
|
1347
1347
|
|
|
1348
1348
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
1349
|
-
`;var
|
|
1350
|
-
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),w=Number(c[3]),P=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:d,type:P})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function
|
|
1349
|
+
`;var Kl=null,ln=null;async function Xl(){return Kl||(Kl=(async()=>{let n=(await import("@sqlite.org/sqlite-wasm")).default;return n()})()),Kl}function rA(n){return{all(e,...t){let r=n.prepare(e);t.length>0&&r.bind(t);let i=[];for(;r.step();)i.push(r.get({}));return r.finalize(),i}}}async function iA(n){let e=await tA(n);if(ln&&ln.dbPath===n&&ln.mtimeMs===e.mtimeMs)return ln.db;ln?.db.close();let t=await Xl(),r=t.capi,i=t.wasm,o=new Uint8Array(await eA(n)),s=i.allocFromTypedArray(o),a=new t.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,o.byteLength,o.byteLength,c),ln={dbPath:n,mtimeMs:e.mtimeMs,db:a},a}function Kh(){ln?.db.close(),ln=null}async function oA(n,e,t,r){n.exec("BEGIN");for(let i of r){let o=t(i.source);e.bind([o,i.source.sectionTitle,i.source.leadText,i.searchText,i.source.excerptTruncated?1:0]),e.step(),e.reset()}n.exec("COMMIT")}function sA(n,e,t){return r=>{let i=e.get(r.documentId);if(i!==void 0)return i;let o=n.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(o!=null){let a=Number(o);return e.set(r.documentId,a),a}t.bind([r.documentId,r.catalogId,r.docTitle]),t.step(),t.reset();let s=Number(n.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function aA(n,e,t){await Yi();let r=await Xl(),i=new r.oo1.DB(":memory:","c");i.exec(Jh);let o=new Map,s=i.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=i.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=sA(i,o,s),l=e.length;for(let g=0;g<l;g+=bl){let w=e.slice(g,g+bl),P=await Promise.all(w.map(async O=>({source:O,searchText:await jh(O)})));await oA(i,a,c,P),await t?.(Math.min(g+w.length,l),l)}i.exec("ANALYZE");let d=r.capi.sqlite3_js_db_export(i);await nA(n,d),i.close(),Kh()}async function cA(n,e,t,r,i,o){let s=await iA(n);return Yh(rA(s),e,t,r,i,o)}async function Xh(){return await Xl(),{resetCache:Kh,buildSearchIndex:aA,searchIndex:(n,e,t,r,i,o,s)=>cA(r,e,t,i,o,s)}}var la=null,Zl=null;async function Ql(){return la||(la=Xh().then(n=>(Zl=n,n))),la}function ed(){Zl?.resetCache(),la=null,Zl=null}async function lA(n,e,t,r,i,o,s){let a=await Ql(),c=s??on();return a.searchIndex(n,e,t,c,r,i,o)}function Or(){ed()}function Qh(n,e,t){let r=new Set,i=[];for(let o of[...n,...e])if(!r.has(o.documentId)&&(r.add(o.documentId),i.push(o),i.length>=t))break;return i}function da(n,e,t,r,i,o){return lA(n,e,t,i,r.expandedQuery,r.rawQuery,o)}async function dA(n,e,t,r,i){let o=await da(n,e,t,r,Wi(r.tokens,"AND"),i);if(o.length>=t)return o;let s=await da(n,e,t,r,Wi(r.tokens,"OR"),i);return Qh(o,s,t)}async function td(n,e,t,r,i){return r.ftsMatch?da(n,e,t,r,r.ftsMatch,i):r.preferAnd?dA(n,e,t,r,i):da(n,e,t,r,Wi(r.tokens,"OR"),i)}async function uA(n,e,t,r){let i=await td(n,"harmonyos-references",e,t,r);if(i.length>=e)return i;let o=await td(n,void 0,e,t,r);return Qh(i,o,e)}function Zh(n,e){return e!==void 0?n:Bh(n)}async function nd(n,e,t=10,r){let i=await Hh(n);if(Oh(i.rawQuery,e)){let a=await uA(n,t,i,r);return Zh(a,e)}let o=e??Gh(i.rawQuery),s=await td(n,o,t,i,r);return Zh(s,e)}var ua=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function fA(n){return new Promise(e=>setTimeout(e,n))}async function eg(n,e,t){e?.start(t),await $i({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await uh(n),Or(),e&&(e.text="Documentation index installed.")}async function mA(n,e){try{return await eg(n,e,"Installing documentation index\u2026"),await tg(e),!0}catch(t){if(Nr(t))throw t}try{return await ph(),Or(),await eg(n,e,"Retrying documentation index install\u2026"),await tg(e),!0}catch(t){if(Nr(t))throw t;return!1}}async function tg(n){await $i({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function hA(n){let e=await jl(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await $i({state:"done",message:t,error:null})}async function gA(n,e){let t=n instanceof Error?n.message:String(n);throw await $i({state:"error",error:t}),e?.fail(t),n}async function yA(){let n=ge();await Ki.promises.mkdir(n,{recursive:!0});let e=Zs();return Ki.existsSync(e)||await Ki.promises.writeFile(e,"","utf-8"),e}async function wA(){let n=await yA();return pA.lock(n,{stale:1800*1e3})}async function vA(){let n=sn(),e=(n?await ji(n):null)??await Fl();if(!e)throw new Error("docs.zip not found");return e}async function SA(n,e){let t=await vA(),r=n.force||await Hl(n.force),i=await ra(n.force);if(!r&&!i&&Ui()){await hA(e);return}if(!(dh(t)&&await mA(t,e)))throw new Error("Documentation index bundle is unavailable or corrupted. Reinstall the package with: npm uninstall -g @deveco/deveco-cli && npm install -g <package.tgz>")}var Mr=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:rg({text:"Checking documentation\u2026",color:"cyan"}),o;try{e.assumeStorageSafe||await Lr({mode:"write"}),o=await wA(),await _l(yh("Starting documentation setup\u2026")),await SA(e,i)}catch(s){throw o&&await gA(s,i),s}finally{o&&await o()}}};async function EA(n){for(;;){let e=await na();if(e.state==="done"&&Ui())return;if(e.state==="error")throw new ua("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 fA(500)}}async function ng(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Mr.run({builtBy:"doc-init",force:e,quiet:!0})}async function bA(){let n=await ra()!==null;if(Ui()&&!n)return;let e=rg({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await wh()){await EA(e),e.succeed("Documentation ready.");return}if(await Hl()){await ng(e),e.succeed("Documentation ready.");return}await ng(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function _r(){await Lr({mode:"read"}),await bA()}function PA(n){let e=n instanceof Error?n.message:String(n);return/file is not a database|database disk image is malformed|SQLITE_CORRUPT/i.test(e)}var rd=class{async search(e,t,r=10){await _r();try{return await nd(e,t,r)}catch(i){if(!PA(i))throw i;return Or(),await Mr.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),nd(e,t,r)}}async readDocument(e){return await _r(),Al(e)}},pa=new rd;import C2 from"adm-zip";import{unified as o2}from"unified";import a2 from"remark-parse";import l2 from"remark-gfm";import{toString as u2}from"mdast-util-to-string";function ig(...n){return e=>{if(!n.includes(e))throw new id(`Allowed values: ${n.join(", ")}`);return e}}function AA(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new id("Must be a positive integer.");return e}var DA=ig("json","default"),RA=ig("json","default");function od(n){let e=n instanceof Error?n.message:String(n);return Nr(n)?e:/\b(EACCES|EPERM|ENOSPC|ENOTDIR|ELOOP)\b/.test(e)?"Documentation data directory is unavailable. Check DEVECO_CLI_DATA_DIR and retry.":e}var ma=new CA("docs").description("Search and read HarmonyOS documentation from local docs directory");ma.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",TA,"all").option("--format <fmt>","Output format (default, json)",DA,"default").option("--limit <n>","Max number of results",AA,10).action(async(n,e)=>{try{let t=kA(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await pa.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):xA(i)}catch(t){console.error(fa(od(t))),process.exit(1)}});ma.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(fa("Document ID cannot be empty.")),process.exit(1));let t=await pa.readDocument(e);console.log(t)}catch(e){console.error(fa(od(e))),process.exit(1)}});ma.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",RA,"default").action(async n=>{try{if(await _r(),n.format==="json"){let e=Tt.map(t=>({name:t,title:nn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Tt)console.log(` ${e.padEnd(20)} ${IA(nn[e])}`)}catch(e){console.error(fa(od(e))),process.exit(1)}});function kA(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>Rr)throw new Error(`Query exceeds ${Rr} characters.`);return e}function TA(n){if(n==="all")return"all";if(!Tt.includes(n))throw new id(`Invalid catalog "${n}". Allowed: all, ${Tt.join(", ")}`);return n}function xA(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 og=ma;import{Command as LD}from"commander";import{Command as WA,InvalidArgumentError as GA,Option as ad}from"commander";import{readFileSync as LA,unlinkSync as OA}from"fs";import{tmpdir as MA}from"os";import{join as _A}from"path";var Nt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=NA(t);return e?.all||(r=r.filter(i=>i.type===1)),r}async fetchDump(){let e=["-t",this.serial,"shell","hidumper","-s","WindowManagerService","-a","-a"];m(`Executing: ${this.hdcPath} ${e.join(" ")}`);let t=await X(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function NA(n){let e=n.split(`
|
|
1350
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),g=Number(c[2]),w=Number(c[3]),P=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(g)&&r.push({id:w,name:l,pid:g,displayId:d,type:P})}let i=e.find(s=>s.trim().startsWith("Focus window")),o=i?Number(i.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===o}))}function sg(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function Xi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function ag(n){if(typeof n!="string")return;let e=n.match(/-?\d+/g);if(!(!e||e.length<4))return[Number(e[0]),Number(e[1]),Number(e[2]),Number(e[3])]}function cg(n){return n.originalText||void 0}function Fr(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let i=r.pop();i.id===e&&t.push(i);for(let o=i.children.length-1;o>=0;o--)r.push(i.children[o])}return t}function lg(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:i,parent:o,depth:s}=r.pop(),a=o===null,c=!i.id&&!i.text&&!i.clickable&&!i.longClickable&&!i.scrollable&&!i.checkable,l=a||!c,d=o;if(l){let w={...i,children:[]};if(a?t.push(w):o.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=i.type?i.id?`${i.type}#${i.id}`:i.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let g=l?s+1:s;for(let w=i.children.length-1;w>=0;w--)r.push({current:i.children[w],parent:d,depth:g})}return t}function FA(n){let e=LA(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function jA(n){return n.attributes??{}}function ha(n,e,t){let r=jA(n),i={id:r.id||void 0,type:r.type||void 0,text:cg(r),bounds:ag(r.bounds),clickable:Xi(r.clickable)||void 0,longClickable:Xi(r.longClickable)||void 0,scrollable:Xi(r.scrollable)||void 0,checkable:Xi(r.checkable)||void 0,hitTestBehavior:sg(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(i.children=n.children.map(o=>ha(o,e,t+1))),i}function HA(n,e){if(e){let r=n.find(i=>String(i.id)===e);if(!r){let i=n.map(o=>`${o.id} (${o.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${i||"none"}`)}return r}let t=n.find(r=>r.focused);if(t)return t;throw new Error("No window id specified and could not detect focused window")}var Hn=class{hdcPath;constructor(e){this.hdcPath=e}buildRemoteDumpPath(){return`/data/local/tmp/deveco_cli_dump_${Date.now()}_${process.pid}.json`}async fetchRawDump(e,t,r){let i=this.buildRemoteDumpPath(),o=["-t",e,"shell","uitest","dumpLayout","-p",i];r!==void 0&&o.push("-d",String(r)),t&&o.push("-w",t),m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let s=await X(this.hdcPath,o);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,i)}async recvAndParseDump(e,t){let r=_A(MA(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),FA(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let i=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let o=await X(this.hdcPath,i);if(o.exitCode!==0)throw new Error(`Failed to recv dump file: ${(o.stderr||o.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),OA(t)}catch(o){m(`Failed to clean local dump file ${t}: ${o.message}`)}let i=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${i.join(" ")}`),await X(this.hdcPath,i).catch(o=>{m(`Failed to clean remote dump file ${r}: ${o.message}`)})}async dumpRawNodes(e,t,r){let o=await new Nt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(o.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=HA(o,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).map(s=>ha(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let i=[];for(let o of r){let s=await this.fetchRawDump(e,void 0,o);i.push({displayId:o,tree:ha(s,t,0)})}return i}async dumpCollapsedTree(e,t,r,i){return(await this.dumpRawNodes(e,r,i)).flatMap(s=>lg(ha(s,0,0),t))}};var ga={left:"0",right:"1",up:"2",down:"3"};function ve(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function sd(n,e){n!==void 0&&ve(n,e)}function dg(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function ya(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function Zi(n){if(n===void 0)return;let e=Number(n);if(!Number.isInteger(e)||e<200||e>4e4)throw new Error("--speed must be an integer between 200 and 40000");return n}function ug(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function pg(n,e,t,r=!0){if(t&&!e)throw new Error("--window must be used with --id");if(n&&e)throw new Error("Coordinates and --id are mutually exclusive");if(r&&!n&&!e)throw new Error("Either provide x y coordinates or use --id")}function jr(n,e,t,r,i=!0){dg(n,e),ya(t,"--id"),sd(n,"x"),sd(e,"y"),ug(r),pg(n!==void 0,!!t,!!r,i)}async function dn(n,e){let r=await new ur(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function gt(n){let e=await A.new(),t=await dn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function Hr(n,e,t,r,i,o){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(i===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Nt(n,e).listWindows({all:!0}),c=new Hn(n);return $A(c,e,a,i,o)}async function $A(n,e,t,r,i){if(i!==void 0){let o=t.find(a=>String(a.id)===i);if(o&&o.displayId!==0)throw new Error(`Window "${i}" is on display ${o.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,i,!1);return BA(s,r)}return UA(n,e,t,r)}async function UA(n,e,t,r){let i=[...new Set(t.map(a=>a.displayId))],o=await n.dumpFullTreeByDisplays(e,0,i),s=[];for(let{displayId:a,tree:c}of o)for(let l of Fr([c],r))s.push({node:l,displayId:a});if(s.length===0)throw new Error(`Node "${r}" not found.`);if(s.length>1)throw new Error(`Multiple nodes found with id "${r}".`);if(s[0].displayId!==0)throw new Error(`Node "${r}" is on display ${s[0].displayId}. The current command only supports operations on the primary display.`);return fg(s[0].node,r)}function BA(n,e){let t=Fr(n,e);if(t.length===0)throw new Error(`Node "${e}" not found.`);if(t.length>1)throw new Error(`Multiple nodes found with id "${e}".`);return fg(t[0],e)}function fg(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,i,o,s]=t;return{x:Math.ceil((r+o)/2),y:Math.ceil((i+s)/2)}}async function Ve(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let i=await X(n,r);if(i.exitCode!==0)throw new Error(i.stderr||i.stdout||`uitest exited with code ${i.exitCode}`);let o=i.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>o.includes(a))&&!o.includes("no error"))throw new Error(i.stdout.trim()||"uitest command failed")}import VA from"ora";function zA(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new GA("depth must be a non-negative integer");return e}function qA(n){let e=[];(n.type||n.id)&&e.push(n.type?n.id?`${n.type}#${n.id}`:n.type:`#${n.id}`),e.push(n.bounds?`[${n.bounds.join(",")}]`:"[]"),n.text&&e.push(`"${JSON.stringify(n.text).slice(1,-1)}"`);let t=[];return n.clickable&&t.push("clickable"),n.longClickable&&t.push("longClickable"),n.scrollable&&t.push("scrollable"),n.checkable&&t.push("checkable"),t.length>0&&e.push(...t),e.join(" ")}function mg(n,e=0){let t=[],r=" ".repeat(e);for(let i of n)t.push(`${r}${qA(i)}`),i.children.length>0&&t.push(...mg(i.children,e+1).split(`
|
|
1351
1351
|
`));return t.join(`
|
|
1352
|
-
`)}function
|
|
1353
|
-
`).trim()}function
|
|
1352
|
+
`)}function YA(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function JA(n,e){let t=Fr(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(i=>({...i,children:[]}));console.log(JSON.stringify(r,null,2))}function KA(n,e){console.log(e==="json"?JSON.stringify(n,null,2):mg(n))}async function XA(n){YA(n);let e=VA({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await dn(r,n.device),o=new Hn(r.hdcPath);t=n.mode==="full"?await o.dumpFullTree(i,n.depth,n.window,n.allWindows):await o.dumpCollapsedTree(i,n.depth,n.window,n.allWindows)}catch(r){throw e.stop(),new Error(`Failed to dump layout: ${r.message}`,{cause:r})}if(e.stop(),n.id){JA(t,n.id);return}KA(t,n.format)}var hg=new WA("layout").description("Inspect on-screen node(s) for UI testing").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Layout node id").option("--window <windowId>","Target window id").option("--all-windows","Include all windows (mutually exclusive with --window)").addOption(new ad("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(zA).default(0)).addOption(new ad("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new ad("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await XA(n)});import{Command as ZA,Option as QA}from"commander";import{yellow as eD}from"colorette";import tD from"ora";var nD=["Id","Name","Pid","DisplayId","Focused"];function rD(n,e){if(e==="json"){let r=n.map(i=>({id:i.id,name:i.name,pid:i.pid,displayId:i.displayId,focused:i.focused}));console.log(JSON.stringify(r,null,2));return}let t=n.map(r=>({cells:[String(r.id),r.name,String(r.pid),String(r.displayId),String(r.focused)],highlight:r.focused}));console.log(bt(nD,t))}async function iD(n){let e=tD({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await A.new(),i=await dn(r,n.device);t=await new Nt(r.hdcPath,i).listWindows({all:n.all})}catch(r){throw e.stop(),new Error(`Failed to list windows: ${r.message}`,{cause:r})}if(e.stop(),t.length===0){console.log(eD(" No windows found."));return}rD(t,n.format)}var cd=new ZA("window").description("Manage device windows");cd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new QA("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await iD(n)});import{Command as oD}from"commander";import Ie from"fs";import ze from"path";import{randomUUID as sD}from"crypto";import{green as aD}from"colorette";function cD(){return String(Date.now())}function gg(n){let e;try{e=Ie.statSync(n)}catch(t){let r=t.code;throw r==="ENOENT"?new Error(`Screenshot directory does not exist: ${n}`,{cause:t}):r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${n}`,{cause:t}):new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}if(!e.isDirectory())throw new Error(`Screenshot parent path is not a directory: ${n}`);try{Ie.accessSync(n,Ie.constants.W_OK|Ie.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function yg(n,e){try{throw Ie.lstatSync(n),new Error(`Screenshot file already exists: ${n}`)}catch(t){let r=t.code;if(r==="ENOENT")return;throw r==="EACCES"||r==="EPERM"?new Error(`Screenshot directory is not writable: ${e}`,{cause:t}):t instanceof Error&&!r?t:new Error(`Invalid screenshot path: ${t.message}${r?` (${r})`:""}`,{cause:t})}}function lD(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=ze.resolve(e);try{if(Ie.statSync(t).isDirectory()){gg(t);let i=ze.join(t,`screenshot-${cD()}.png`);return yg(i,t),i}}catch(i){if(i.code!=="ENOENT")throw i}if(ze.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=ze.dirname(t);return gg(r),yg(t,r),t}function wg(n){if(!Ie.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Ie.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Ie.readFileSync(n).subarray(0,8),r=Buffer.from([137,80,78,71,13,10,26,10]);if(!t.equals(r))throw new Error(`Screenshot file is not a valid PNG: ${n}`)}function dD(n,e){let t=["-t",n.serial,"shell","snapshot_display"];return n.display!==void 0&&t.push("-i",n.display),t.push("-f",n.remotePath),e&&t.push("-t",e),t}function uD(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function pD(n,e){try{Ie.copyFileSync(n,e,Ie.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}wg(e)}function fD(n){let e=n.trim();if(!e||/No such file|not found|cannot access/i.test(e))return;let t=e.split(/\s+/),r=Number(t[4]);return Number.isFinite(r)?r:void 0}async function mD(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await X(n.hdcPath,e);return t.exitCode===0?fD(t.stdout):void 0}function hD(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1353
|
+
`).trim()}function gD(n){let e=String.raw`invalid|not found|not exist|does not exist|out of range|unsupported`;return new RegExp(String.raw`display(?:\s*id)?.*(?:${e})`,"is").test(n)||new RegExp(String.raw`(?:${e}).*display(?:\s*id)?`,"is").test(n)}async function yD(n,e){let t=dD(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await X(n.hdcPath,t),i=await mD(n);return{created:i!==void 0&&i>0,output:hD(r)}}async function wD(n){let e="";for(let t of[void 0,"png"]){let r=await yD(n,t);if(r.created)return;if(n.display!==void 0&&gD(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
|
|
1354
1354
|
snapshot_display output:
|
|
1355
1355
|
${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
|
|
1356
1356
|
snapshot_display output:
|
|
1357
|
-
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function
|
|
1357
|
+
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function vg(n){try{return wg(n),!0}catch{return!1}}function Sg(n){let e=[];for(let t of Ie.readdirSync(n,{withFileTypes:!0})){let r=ze.join(n,t.name);if(t.isDirectory()){e.push(...Sg(r));continue}t.isFile()&&vg(r)&&e.push(r)}return e}function vD(n,e){let t=ze.join(n,ze.basename(e));if(vg(t))return t;let r=Sg(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function ld(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let i=await X(n.hdcPath,r);return i.exitCode!==0&&m(`hdc file recv failed: ${i.stderr||i.stdout||`exit code ${i.exitCode}`}`),vD(e,n.remotePath)}async function SD(n){let e=Ie.mkdtempSync(ze.join(ze.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await ld(n,e,ze.join(e,ze.basename(n.remotePath)))??await ld(n,e,e)??await ld(n,e,ze.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);pD(t,n.localPath)}finally{Ie.rmSync(e,{recursive:!0,force:!0})}}async function ED(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await X(n.hdcPath,e)}async function bD(n){try{await wD(n),await SD(n)}finally{await ED(n)}}async function PD(n){let e=lD(n.path),t=n.display!==void 0?uD(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let r=await A.new(),i=await dn(r,n.device),o=`/data/local/tmp/devecocli-${sD()}.png`;await bD({hdcPath:r.hdcPath,serial:i,localPath:e,remotePath:o,display:t}),console.log(aD(`Screenshot saved to ${e}`))}var Eg=new oD("screenshot").description("Capture a screenshot of the device screen").option("--device <name|serial>","Target device name or serial; required when multiple devices are connected").option("--display <displayId>","Target display id; omit for default screen").option("--path <path>","Required directory or PNG file path; destination must be writable").action(PD);import{Command as un}from"commander";function CD(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function pn(n,e,t){let r=new tt;r.start(n);try{await t(r)}catch(i){throw r.stop(),new Error(`${e}: ${i.message}`,{cause:i})}}async function ID(n,e,t){await pn("Executing click...","click failed",async r=>{jr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await gt(t.device),{x:s,y:a}=await Hr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ve(i,o,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function AD(n,e,t){await pn("Executing doubleclick...","doubleclick failed",async r=>{jr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await gt(t.device),{x:s,y:a}=await Hr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ve(i,o,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function DD(n,e,t){await pn("Executing longclick...","longclick failed",async r=>{jr(n,e,t.id,t.window);let{hdcPath:i,deviceId:o}=await gt(t.device),{x:s,y:a}=await Hr(i,o,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ve(i,o,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function RD(n,e,t,r,i){await pn("Executing swipe...","swipe failed",async o=>{ve(n,"x1"),ve(e,"y1"),ve(t,"x2"),ve(r,"y2");let s=Zi(i.speed),{hdcPath:a,deviceId:c}=await gt(i.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Ve(a,c,l),o.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function kD(n,e,t,r,i){await pn("Executing fling...","fling failed",async o=>{ve(n,"x1"),ve(e,"y1"),ve(t,"x2"),ve(r,"y2");let s=Zi(i.speed),{hdcPath:a,deviceId:c}=await gt(i.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Ve(a,c,l),o.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function TD(n,e,t,r,i){await pn("Executing drag...","drag failed",async o=>{ve(n,"x1"),ve(e,"y1"),ve(t,"x2"),ve(r,"y2");let s=Zi(i.speed),{hdcPath:a,deviceId:c}=await gt(i.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Ve(a,c,l),o.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function xD(n,e){await pn("Executing dircfling...","dircfling failed",async t=>{let r=ga[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(ga).join(", ")}`);let{hdcPath:i,deviceId:o}=await gt(e.device);await Ve(i,o,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function ND(n,e,t,r){await pn("Executing text input...","input failed",async i=>{jr(e,t,r.id,r.window,!1),ya(n,"text");let{hdcPath:o,deviceId:s}=await gt(r.device),a=CD(n);if(e!==void 0)await Ve(o,s,["uitest","uiInput","inputText",`${e}`,`${t}`,a]),i.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:c,y:l}=await Hr(o,s,void 0,void 0,r.id,r.window);await Ve(o,s,["uitest","uiInput","inputText",`${c}`,`${l}`,a]),i.succeed(`input ${n} at (${c}, ${l})`)}else await Ve(o,s,["uitest","uiInput","text",a]),i.succeed(`input ${n}`)})}var bg=new un("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(ID),Pg=new un("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(AD),Cg=new un("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(DD),Ig=new un("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(RD),Ag=new un("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(kD),Dg=new un("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(TD),Rg=new un("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(xD),kg=new un("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(ND);var qe=new LD("ui").description("Inspect and interact with UI on a connected device");qe.addCommand(hg);qe.addCommand(cd);qe.addCommand(Eg);qe.addCommand(bg);qe.addCommand(Pg);qe.addCommand(Cg);qe.addCommand(Ig);qe.addCommand(Ag);qe.addCommand(Dg);qe.addCommand(Rg);qe.addCommand(kg);var Tg=qe;import{Command as sy,InvalidArgumentError as mk}from"commander";import{execa as tR}from"execa";import Lt from"fs";import*as fd from"os";import*as W from"path";var OD=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),MD=/\r/g,_D=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,FD=/^<+\s*/,jD=/\s*>+$/,HD=[/^The configuration file .+ is in use\.$/,/^The configuration file .+ in the project is in use\.$/,/^Currently active product: ?.+$/,/^Writing the result to .+\.$/,/^Write finished\.$/,/^CodeLinter found some defects in your code\.$/];function dd(n){if(!n)return"";let e=n.replace(OD,"").replace(MD,`
|
|
1358
1358
|
`).split(`
|
|
1359
|
-
`).map(t=>t.trimEnd()).filter(t=>
|
|
1359
|
+
`).map(t=>t.trimEnd()).filter(t=>UD(t));return e.length>0?`${e.join(`
|
|
1360
1360
|
`)}
|
|
1361
|
-
`:""}function
|
|
1361
|
+
`:""}function Og(n){let e=dd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Mg(e))return{jsonText:e,diagnostics:""};let t=BD(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
|
|
1362
1362
|
`};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
|
|
1363
1363
|
`);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
|
|
1364
|
-
`:""}}function
|
|
1365
|
-
${
|
|
1366
|
-
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[
|
|
1364
|
+
`:""}}function $D(n){return _D.test(n.trim())}function UD(n){let e=n.trim();return!!e&&!$D(e)&&!HD.some(t=>t.test(e))}function Mg(n){try{return JSON.parse(n),!0}catch{return!1}}function BD(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=WD(n,e);if(t)return t}}function WD(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let i=n.slice(e,t);if(Mg(i))return{start:e,end:t}}}var xg=["Error","Warning","Suggestion","Info","Off","Unknown"];function _g(n){let e=ud(n);return{issues:qD(e),summary:GD(n,e)}}function GD(n,e){let t=JD(e);return{filesChecked:KD(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function ud(n,e=""){if(Array.isArray(n))return n.flatMap(o=>ud(o,e));if(!Fg(n))return[];let t=Qi(n,["filePath","file","path"])??e,r=VD(n,t);if(r.length>0)return r;let i=zD(n,t);return i?[i]:[]}function VD(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let i=n[r];if(Array.isArray(i)){let o=i.flatMap(s=>ud(s,e));if(o.length>0)return o}}return[]}function zD(n,e){let t=Qi(n,["message","description","desc","detail"])??"",r=eR(Qi(n,["rule","ruleId","ruleName"])),i=ZD(n,["severity","level"]),o=Qi(n,["filePath","file","path"])??e;if(!(!t&&!r&&i==="Unknown"))return{file:o,line:Lg(n,["line","reportLine"]),column:Lg(n,["column","reportColumn"]),severity:i,rule:r,message:t}}function qD(n){return[...n].sort((e,t)=>{let r=Ng(e.severity)-Ng(t.severity);return r===0?YD(e,t):r})}function YD(n,e){let t=n.file.localeCompare(e.file);if(t!==0)return t;let r=(n.line??Number.MAX_SAFE_INTEGER)-(e.line??Number.MAX_SAFE_INTEGER);return r!==0?r:(n.column??Number.MAX_SAFE_INTEGER)-(e.column??Number.MAX_SAFE_INTEGER)}function JD(n){let e=new Map;for(let t of n){let r=t.severity;e.set(r,(e.get(r)??0)+1)}return e}function KD(n){let e=new Set;return pd(e,n,""),e}function pd(n,e,t){if(Array.isArray(e)){for(let i of e)pd(n,i,t);return}if(!Fg(e))return;let r=Qi(e,["filePath","file","path"])??t;r&&n.add(r),XD(n,e,r)}function XD(n,e,t){let r=["messages","defects","issues","results","files"];for(let i of r){let o=e[i];if(Array.isArray(o))for(let s of o)pd(n,s,t)}}function ZD(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return QD(r)}return"Unknown"}function QD(n){let e=String(n).normalize("NFKC").trim().toLowerCase();return e==="2"||e==="error"||e==="err"?"Error":e==="1"||e==="warn"||e==="warning"?"Warning":e==="3"||e==="suggest"||e==="suggestion"?"Suggestion":e==="info"||e==="information"?"Info":e==="0"||e==="off"?"Off":"Unknown"}function eR(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(FD,"").replace(jD,"").toLowerCase()}function Ng(n){let e=xg.indexOf(n);return e===-1?xg.length:e}function Qi(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Lg(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Fg(n){return typeof n=="object"&&n!==null}var jg="deveco-codelinter-",Hg=[".ets",".ts",".js"],eo=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return V.discover(e).rootDir}catch{return e}}async check(e){let t=Lt.mkdtempSync(W.join(fd.tmpdir(),jg)),r=W.join(t,"report.json");try{let i=n.resolveProjectRoot(this.cwd),o=this.resolveLintTarget(e.lintPath,i),s=this.resolveConfigPath(e.configPath,o),a=this.buildNativeArgs(e,o.path,s,r),c=await this.run(a),l=Og(c.stdout),d=l.diagnostics+dd(c.stderr);try{let g=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:_g(g)}}catch(g){return{exitCode:c.exitCode,diagnostics:d,reportError:g}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?W.resolve(this.cwd,e):t,i=this.resolveRealPath(r,"Lint path"),o=Lt.statSync(i);if(!o.isFile()&&!o.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(o.isFile()){let a=W.extname(i).toLowerCase();if(!Hg.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${i}. Supported extensions: ${Hg.join(", ")}.`)}let s=this.discoverProjectRoot(i,o.isDirectory());if(e!==void 0&&s===void 0)throw new Error(`Lint path is not in a valid project directory (project-level build-profile.json5 not found or invalid): ${i}`);return{path:i,projectRoot:s}}resolveConfigPath(e,t){let r=e?W.resolve(this.cwd,e):W.join(t.projectRoot??this.cwd,"code-linter.json5"),i=this.resolveRealPath(r,"`--config-path`");if(!Lt.statSync(i).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let o=this.discoverProjectRoot(i,!1);if(o===void 0||W.relative(t.projectRoot,o)!=="")throw new Error(`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${o??"not found"}.`)}return i}discoverProjectRoot(e,t){let r=t?e:W.dirname(e);try{return Lt.realpathSync(V.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Lt.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,i){let o=["--config",r];return e.fix&&o.push("--fix"),e.incremental&&o.push("--incremental"),o.push("--product",e.product,"--format","json","--output",i,t),o}async run(e){let t=[...this.resolution.argsPrefix,...e],r=this.resolution.workingDirectory??this.cwd;this.prepareRuntimeDirectories(),m(`Executing: ${this.resolution.command} ${t.join(" ")}`),m(`[CodelinterAdapter] Working directory: ${r}`);let i=await tR(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:i.exitCode??1,stdout:i.stdout,stderr:i.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Lt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let i=(Lt.existsSync(e)?Lt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!i)throw new Error("Native JSON report was not generated.");return JSON.parse(i)}removeTempDir(e){let t=W.resolve(e),r=W.resolve(fd.tmpdir());!(t.startsWith(`${r}${W.sep}`)||t===r)||!W.basename(t).startsWith(jg)||Lt.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,i=e.codelinterPath,o=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c={command:e.nodePath,argsPrefix:[i,o],env:{...process.env,PATH:[...s,process.env.PATH||""].join(W.delimiter),DEVECO_SDK_HOME:o}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(i)]),m(`[CodelinterAdapter] Selected ${a} entry: ${i}`),c}static getPathEntries(e,t){let r=[W.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(W.dirname(e.javaPath)),r}static getResultDirectory(e){return W.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as va,yellow as pR}from"colorette";import{Argument as fR,Command as mR,InvalidArgumentError as mn}from"commander";import no from"fs";import*as Ae from"path";import*as to from"path";var $g="n/a",Ug=/\\/g,nR=/\|/g,rR=/\r?\n/g;function Bg(n,e){if(n.issues.length===0)return`No defects found.
|
|
1365
|
+
${md(n.summary)}
|
|
1366
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[oR(t),md(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(iR(n.issues.length,t.length)),`${r.join(`
|
|
1367
1367
|
`)}
|
|
1368
|
-
`}function
|
|
1369
|
-
`)}function
|
|
1370
|
-
`)}function
|
|
1371
|
-
`}function
|
|
1372
|
-
`)}function
|
|
1373
|
-
`))}}var
|
|
1374
|
-
`?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function
|
|
1368
|
+
`}function Wg(n,e){return[md(n.summary),`Full report: ${hd(e)}`,""].join(`
|
|
1369
|
+
`)}function Gg(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...sR(n.issues),""),e.push("## Summary","",...cR(n.summary),""),e.join(`
|
|
1370
|
+
`)}function Vg(n){return`${JSON.stringify(n,null,2)}
|
|
1371
|
+
`}function md(n){return`Summary: Issues: ${Ye(n.issues)} | Errors: ${Ye(n.errors)} | Warnings: ${Ye(n.warnings)} | Suggestions: ${Ye(n.suggestions)} | Files checked: ${Ye(n.filesChecked)}`}function iR(n,e){return`Showing ${Ye(e)} of ${Ye(n)} issues. Use --output-path <path> to write all results.`}function oR(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,i)=>({cells:dR(r,i+1)}));return["CodeLinter report","",bt(e,t)].join(`
|
|
1372
|
+
`)}function sR(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(aR(r,t+1));return e}function aR(n,e){return`| ${[String(e),hd(fn(n.file)),wa(n.line),wa(n.column),fn(n.severity),fn(n.rule),fn(n.message)].map(lR).join(" | ")} |`}function cR(n){return[`- Issues: ${Ye(n.issues)}`,`- Errors: ${Ye(n.errors)}`,`- Warnings: ${Ye(n.warnings)}`,`- Suggestions: ${Ye(n.suggestions)}`,`- Files checked: ${Ye(n.filesChecked)}`]}function lR(n){return n.replace(Ug,"\\\\").replace(nR,"\\|").replace(rR,"<br>")}function dR(n,e){return[String(e),hd(fn(uR(n.file))),wa(n.line),wa(n.column),fn(n.severity),fn(n.rule),fn(n.message)]}function uR(n){if(!to.isAbsolute(n))return n;let e=to.relative(process.cwd(),n);return!e||e.startsWith("..")||to.isAbsolute(e)?n:e}function hd(n){return n.replace(Ug,"/")}function fn(n){let e=n?.trim();return e||$g}function wa(n){return n===void 0?$g:String(n)}function Ye(n){return n.toLocaleString("en-US")}var hR=/^-?\d+$/;function gd(){return new mR("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").helpOption("--help","display help for command").addArgument(new fR("[path]","File or directory to lint").argParser(SR)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",yR).option("--product <product>","Product name defined in build-profile.json5",wR,"default").option("--format <format>","Report format (choices: default, json)",gR,"default").option("--output-path <path>","Complete report file or directory",vR).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",ER).action(async(n,e)=>{await bR(n,e)})}function gR(n){if(n==="default"||n==="json")return n;throw new mn("Invalid --format. Expected one of: default, json.")}function yR(n){yd(n,"--config-path");let e=Ae.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new mn("`--config-path` must point to a .json or .json5 file.");return n}function wR(n){return zg(n,"product"),n}function vR(n){return yd(n,"--output-path"),n}function SR(n){return yd(n,"path"),n}function ER(n){if(zg(n,"limit"),!hR.test(n))throw new mn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new mn("`--limit` must be an integer greater than 0.");return e}function zg(n,e){if(n.trim().length===0||Jg(n))throw new mn(`Invalid --${e} value.`)}function yd(n,e){let t=`\`${e}\``;if(n.length===0||Jg(n))throw new mn(`${t} must be a non-empty path without control characters.`)}async function bR(n,e){let t=process.cwd(),r=DR(e.outputPath,e.format,t);e.fix&&console.warn(pR("Running codelinter with --fix. Ensure your project source is trusted."));let i=await PR(n,e,t);NR(i.diagnostics),process.exitCode=IR(i,r,e.format,e.limit,t)}async function PR(n,e,t){let r=await A.new(),i=new eo(r,t);return CR(i,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function CR(n,e){let t=new tt;process.stderr.isTTY&&t.start("Checking code...");try{let r=await n.check(e);return t.stop(),r}catch(r){throw t.fail("Code check failed"),r}}function IR(n,e,t,r,i){if(!n.report)return console.error(va("Failed to generate Code Linter report.")),console.error(va(n.reportError?.message??"Native JSON report was not generated.")),n.exitCode===0?1:n.exitCode;try{if(e){AR(e,t,n.report);let o=Yg(e,i);process.stdout.write(Wg(n.report,o))}else process.stdout.write(Bg(n.report,r));return n.exitCode}catch(o){return console.error(va("Failed to generate Code Linter report.")),console.error(va(o.message)),n.exitCode===0?1:n.exitCode}}function AR(n,e,t){no.mkdirSync(Ae.dirname(n),{recursive:!0});let r=e==="json"?Vg(t):Gg(t);try{no.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(i){throw i.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:i}):i}}function DR(n,e,t){if(!n)return;let r=TR(n,t),i=kR(n,r),o=i?Ae.join(r,xR(e)):r;if(i||RR(n,e),no.existsSync(o))throw new mn(`Output file already exists: ${Yg(o,t)}`);return o}function RR(n,e){let t=qg(e);if(Ae.extname(n).toLowerCase()!==t)throw new mn(`--output-path must use the ${t} extension for --format ${e}.`)}function kR(n,e){return no.existsSync(e)?no.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||Ae.extname(n)===""}function TR(n,e){return Ae.resolve(e,n)}function xR(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((o,s)=>String(o).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(o=>String(o).padStart(2,"0")).join(""),i=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${i}${qg(n)}`}function qg(n){return n==="json"?".json":".md"}function Yg(n,e){let t=Ae.relative(e,n);return t&&!t.startsWith("..")&&!Ae.isAbsolute(t)?t:n}function NR(n){n&&process.stderr.write(n)}function Jg(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{InvalidArgumentError as LR}from"commander";import*as G from"path";import*as wd from"os";import{readdirSync as OR,existsSync as Sa,readFileSync as MR,unlinkSync as _R,copyFileSync as Qg,writeFileSync as ey}from"fs";import{execa as FR}from"execa";import{cyan as de,yellow as ty}from"colorette";import jR from"ora";var HR=["default","csv","json"],Kg=["default","json"];function $R(n){return[...n].sort((e,t)=>{let r=Xg(e),i=Xg(t);return r.apiVersion-i.apiVersion||r.suffix.localeCompare(i.suffix)})}function Xg(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),i=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:i}}function ny(n){let t=OR(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return $R(t)}async function ry(n){if(n=n===void 0?"default":n,!Kg.includes(n))throw new Error(`--format must be ${Kg.join(" or ")}. got "${n}"`);let e=await A.new(),{apiChangeDir:t}=e.getApiscanPaths();m(de(`[compat:versions] apiChangeDir: "${t}"`));let r=ny(t);if(n==="json")console.log(JSON.stringify({versions:r,count:r.length},null,2));else{if(r.length===0){console.log("No SDK versions available.");return}console.log(r.join(`
|
|
1373
|
+
`))}}var Zg=new Set([".ets",".c",".cpp"]);function UR(n,e){let t=new Set(n.profile.modules.map(s=>s.name)),r=e.filter(s=>!t.has(s));if(r.length===0)return;let i=n.profile.modules.map(s=>s.name).join(", "),o=r.length>1?"are":"is";throw new Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${o} not defined in build-profile.json5. Available modules: ${i}.`)}function BR(n){for(let e of n){let t=G.resolve(e);if(!Sa(t))throw new Error(`File "${e}" does not exist.`);let r=G.extname(t).toLowerCase();if(!Zg.has(r)){let i=Array.from(Zg).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${i}.`)}}}function WR(n){let e=[],t=[];for(let r of n)G.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function GR(n){let e=[],t=[],r="",i=!1,o=0;for(;o<n.length;){let s=n[o];i?{field:r,inQuotes:i,i:o}=VR(n,o,s,r,i):s==='"'?(i=!0,o+=1):s===","?(t.push(r),r="",o+=1):s===`
|
|
1374
|
+
`?(t.push(r),e.push(t),t=[],r="",o+=1):(s==="\r"||(r+=s),o+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function VR(n,e,t,r,i){return t!=='"'?{field:r+t,inQuotes:i,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:i,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function zR(n,e){return e.map(t=>{let r=i=>{let o=n.indexOf(i);return o>=0&&o<t.length?t[o]:""};return{apiDefinition:r("Api Definition"),language:r("Language"),changeId:r("ChangeId"),changedInSdk:r("Changed in SDK"),affectedVersions:r("Affected Versions"),title:r("Title"),codeLocation:r("Code Location"),changeType:r("Change Type")}})}function qR(n){let e=MR(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=GR(t);if(r.length<2)return[];let[i,...o]=r;return zR(i,o)}function YR(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return G.isAbsolute(r)?r:G.join(e,r)}function JR(n,e){let t=new Map;for(let o of n){let s=o.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])),i=Math.max(5,...r.map(([o])=>o.length));console.log(de("API change scan summary:")),console.log(` ${"Total".padEnd(i)} ${n.length}`);for(let[o,s]of r)console.log(` ${o.padEnd(i)} ${s}`);e&&console.log(` ${"Report".padEnd(i)} ${e}`)}function KR(n,e){if(console.log(),n.length===0){console.log("No API changes detected.");return}let t=n.slice(0,e),r=n.length-t.length;console.log(de(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let i=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],o=Math.max(...i.map(([a])=>a.length)),s=a=>a||"<unknown>";for(let a of t){console.log(` [${s(a.changeType)}] ${s(a.apiDefinition)}`);for(let[c,l]of i)console.log(` ${c.padEnd(o)} ${s(a[l])}`)}r>0&&console.log(ty(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function XR(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({records:t,count:n.length},null,2)),r>0&&console.log(ty(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function ZR(n,e){let t=[];for(let r of e){let i=n.profile.modules.find(o=>o.name===r);if(!i)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(G.resolve(n.rootDir,i.srcPath))}return t}function QR(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("source-version and target-version are required.");let i=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:o,cpp:s}=WR(e),a=d=>G.resolve(process.cwd(),d),c=o.map(a),l=s.map(a);c.length>0&&i.push("--arkTsFiles",c.join(",")),l.length>0&&i.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let o=ZR(t,r.modules);i.push("--modulePaths",o.join(","))}else i.push("--projectPath",t.rootDir);return i.push("--outputPath",wd.tmpdir()),i}async function ek(n,e){let t=G.dirname(e[0]);try{let i=(await FR(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(de("[compat:check] === scan stdout ===")),process.stdout.write(i),i.endsWith(`
|
|
1375
1375
|
`)||process.stdout.write(`
|
|
1376
1376
|
`),console.log(de("[compat:check] === end stdout ==="))),i}catch(r){let i=r;process.env.DEVECO_CLI_DEBUG&&i.stdout&&(console.log(de("[compat:check] === scan stdout (on error) ===")),process.stdout.write(i.stdout),i.stdout.endsWith(`
|
|
1377
1377
|
`)||process.stdout.write(`
|
|
1378
1378
|
`),console.log(de("[compat:check] === end stdout ===")));let o=new Error(`Compatibility scan failed: ${i.message}`+(i.stderr?`
|
|
1379
|
-
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function
|
|
1380
|
-
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function
|
|
1381
|
-
`}function ek(n,e,t,r){r===".csv"?Jg(n,t):Kg(t,ey(e),"utf8"),m(de(`[compat:check] saved report: "${t}"`))}function tk(n,e,t,r){if(r==="json"){let o=G.basename(n,".csv"),s=G.join(t,`${o}.json`);return Kg(s,ey(e),"utf8"),m(de(`[compat:check] saved report: "${s}"`)),s}let i=G.join(t,G.basename(n));return Jg(n,i),m(de(`[compat:check] saved report: "${i}"`)),i}async function nk(n,e){let t=new Oe(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function rk(n,e){VR(n,e);let t=V.discover(process.cwd());e.modules&&e.modules.length>0&&xR(t,e.modules),n.length>0&&LR(n);let r=await I.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(de(`[compat:check] script: "${o}"`));let s=Zg(i);zR(e,s),e.outputPath&&m(de(`[compat:check] outputPath: "${e.outputPath}"`));let a=ZR(e.outputPath,e.format);return m(de(`[compat:check] outputTarget: ${a.kind}`)),QR(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function ty(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await rk(n,e),s=RR({text:"Running compatibility check...",color:"cyan"}).start();try{await nk(o,e);let a=WR(r,n,t,e);YR(r,a);let c=await GR(o,a),l=jR(c,yd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(de(`[compat:check] tmp csv: "${l}"`));let d=FR(l),g=null;if(i.kind==="file")ek(l,d,i.filePath,i.ext),g=i.filePath;else if(i.kind==="dir")g=tk(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);JR(l),s.stop(),qR(d,g,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}function ok(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new ik(`--limit must be a positive integer (got "${n}")`);return e}function sk(){let n=process.argv;for(let e=0;e<n.length;e++){if(n[e]==="--format"&&e+1<n.length)return n[e+1];if(n[e].startsWith("--format="))return n[e].slice(9)}}var wd=new ny("compat").description("Compatibility checking utilities.");wd.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",ok,100).action(async(n,e)=>{await ty(n,e)});wd.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async()=>{await Qg(sk())});var ak=new ny("check").description("Run DevEco project checks").addCommand(wd).addCommand(hd()),ry=ak;import{Command as qT}from"commander";import{green as Ud,red as YT}from"colorette";import Bd from"fs";import $y from"path";import Uy from"json5";import{readFileSync as Ok}from"fs";import{join as ck}from"path";var K={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},Ae={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:ck(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ue={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},it={FORBIDDEN:403,UNAUTHORIZED:401},v={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},ee={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Sa(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function vd(n){let e=n.replace(Ae.TEAM_ID_INVALID_CHARS,"");return`${Ae.CERT_NAME_PREFIX}${e}.cer`}function $r(n,e,t){if(n===it.FORBIDDEN)return e===ue.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN);if(n===it.UNAUTHORIZED)return new Error(v.ERR_UNAUTHORIZED);if(t.includes(ue.USER_NOT_HARMONY_CODE))return new Error(v.ERR_USER_NOT_HARMONY);if(t.includes(ue.CERT_LIMIT_CODE))return new Error(v.ERR_CERT_LIMIT_REACHED);let r=lk(t);return new Error(r??v.ERR_DOWNLOAD_CER)}function lk(n){let e=iy(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?iy(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function iy(n){try{return JSON.parse(n)}catch{return null}}function Sd(n){return JSON.parse(n)}async function oy(n){let e=`${K.BASE_URL}${K.CERT_LIST_PATH}`,t=await L.postAllowFailure(e,{headers:Sa(n)});if(t.statusCode!==200)throw $r(t.statusCode,t.statusText,t.data);return Sd(t.data)?.certList??[]}async function Ea(n,e){return(await oy(n)).find(r=>r.certName===e)??null}async function Ed(n,e){let t=`${K.BASE_URL}${K.CERT_DELETE_PATH}`,r=await L.deleteAllowFailure(t,{headers:Sa(n),params:{certIds:[e]}});if(r.statusCode!==200)throw $r(r.statusCode,r.statusText,r.data);return Sd(r.data)?.ret?.code===0}async function bd(n,e,t){let r=`${K.BASE_URL}${K.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:Ae.CERT_TYPE_DEBUG},o=await L.postAllowFailure(r,{headers:Sa(n),params:i});if(o.statusCode!==200)throw $r(o.statusCode,o.statusText,o.data);if(!o.data.includes(ue.SUCCESS_MARKER))throw $r(void 0,o.statusText,o.data)}async function Pd(n,e){let t=`${K.BASE_URL}${K.CERT_DOWNLOAD_URL_PATH}`,r=await L.postAllowFailure(t,{headers:Sa(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw $r(r.statusCode,r.statusText,r.data);return Sd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as dk,writeFileSync as uk,existsSync as pk}from"fs";import{dirname as fk}from"path";async function ro(n,e){let{statusCode:t,statusText:r,buffer:i}=await L.getBinaryAllowFailure(n,{timeout:Ae.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===it.FORBIDDEN&&r===ue.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_DOWNLOAD_CER);let o=fk(e);pk(o)||dk(o,{recursive:!0}),uk(e,i)}import xk from"fs/promises";import{readFileSync as Lk}from"fs";import ba from"path";import cy from"crypto";import mk from"os";import io from"fs/promises";var ly={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},sy=["ECC","RSA"],ay=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],hk={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},gk=8,Cd=64,yk=/[\\:*?"<>|=-]/g,ot={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function wk(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>Cd)throw new Error(`The length of keyAlias cannot exceed ${Cd}`);if(!sy.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${sy.join(" / ")}`);let e=hk[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function vk(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!ay.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${ay.join(" / ")}`)}function Sk(n){return cy.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Ek(n){let e=n?.trim()??"";return e&&e.replace(yk,"_").slice(0,Cd)||ot.productName}async function dy(){let n=await I.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=ba.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await io.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function bk(n){let{javaPath:e,jarPath:t}=await dy(),r=["-jar",t,ly.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function Pk(n){let{javaPath:e,jarPath:t}=await dy(),r=["-jar",t,ly.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function Ck(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),wk(n);let e=await bk(n),t=await Xr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function Ik(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),vk(n);let e=await Pk(n),t=await Xr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function Ak(n=gk){return cy.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Dk(){let n=mk.homedir();try{await io.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=ba.join(n,".ohos","config");try{await io.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function ye(n,e,t){let r=Ek(n),i=ba.basename(e),o=Sk(e),s=`${r}_${i}_${o}=.${t}`,a=await Dk();return ba.join(a,s)}function Rk(n){let e;try{e=V.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function kk(n){try{await io.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function Tk(n){try{await io.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Id(n,e,t){let r=process.cwd(),i=Rk(r);await kk(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=Ak(),s=await ye(n??"",i,"p12"),a=await ye(n??"",i,"csr");return console.log("Start generating p12"),await Ck({keyAlias:e?.keyAlias??ot.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??ot.keyAlg,keySize:e?.keySize??ot.keySize,keystoreFile:s,keystorePwd:o}),await Tk(s),console.log("Start generating csr"),await Ik({subject:t?.subject??ot.csrSubject,outFile:a,keyAlias:t?.keyAlias??ot.keyAlias,keyPwd:o,signAlg:t?.signAlg??ot.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??ot.keyAlias}}var Nk=["p12","cer","csr","p7b"];async function Ad(n,e){for(let t of Nk){let r=await ye(n,e,t);await xk.rm(r,{force:!0})}}function Dd(n){let e;try{e=Lk(n,"utf-8")}catch{throw new Error(v.ERR_CERT_INVALIDATE)}if(!Ae.CERT_PATTERN.test(e))throw new Error(v.ERR_CERT_INVALIDATE)}async function uy(n,e){return{certPath:await ye(n,e,"cer"),csrPath:await ye(n,e,"csr"),p12Path:await ye(n,e,"p12"),profilePath:await ye(n,e,"p7b")}}async function Rd(n,e){let t=e??"",r=V.discover(process.cwd()).rootDir;await Ad(t,r);let i=vd(n.teamId),o=await Ea(n,i);if(o&&!await Ed(n,o.id))throw new Error(v.ERR_DOWNLOAD_CER);let s=await Id(e),a;try{a=Ok(s.csrFilePath,"utf-8")}catch{throw new Error(v.ERR_READ_CSR)}console.log("Start generating certificate"),await bd(n,a,i);let c=await Ea(n,i);if(!c)throw new Error(v.ERR_DOWNLOAD_CER);let l=await Pd(n,c.certObjectId);if(!l)throw new Error(v.ERR_DOWNLOAD_CER);let d=await ye(t,r,"cer");await ro(l,d),Dd(d);let g=await ye(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import La from"crypto";import wn from"fs";import*as Ay from"path";import nT from"json5";import{execa as Py}from"execa";import Cy from"node-forge";import{createCipheriv as Mk,createDecipheriv as _k,pbkdf2Sync as Fk,randomBytes as Ld}from"crypto";import{promises as Un}from"fs";import{dirname as jk,join as st}from"path";var Pa=3,oo=16,Hk=1e4,py="material",$k=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),gy="aes-128-gcm",$n=12,Ca=16,hn=4;function kd(n){return new Uint8Array(Ld(n))}function Uk(n){return Ld(n).toString("hex")}function Bk(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function fy(n,e,t=Hk,r=oo){let i=[...n,$k],o=Bk(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=Fk(a,e,t,r,"sha256");return new Uint8Array(c)}function my(n,e){let t=Ld($n),r=Mk(gy,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(hn+$n+s.length);return c.writeUInt32BE(a,0),t.copy(c,hn),s.copy(c,hn+$n),c}function hy(n,e){if(e.length<hn+$n+Ca)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(hn,hn+$n),i=e.subarray(hn+$n,hn+$n+t);if(i.length<Ca)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Ca),s=i.subarray(i.length-Ca),a=_k(gy,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function Wk(n){try{await Un.rm(n,{recursive:!0,force:!0})}catch{}}async function Td(n){let e=await Un.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return Un.readFile(st(n,t[0]))}async function xd(n,e){let t=Uk(oo),r=st(n,t);return await Un.writeFile(r,e),t}var gn=class{static async generateMaterial(e){let t=st(e,py);await Wk(t);let r=st(t,"ac"),i=st(t,"ce");await Un.mkdir(r,{recursive:!0}),await Un.mkdir(i,{recursive:!0});for(let d=0;d<Pa;d++)await Un.mkdir(st(t,"fd",String(d)),{recursive:!0});let o=kd(oo),s=[];for(let d=0;d<Pa;d++)s.push(kd(oo));let a=kd(oo),c=fy(s,o),l=my(c,a);await xd(r,o),await xd(i,l);for(let d=0;d<Pa;d++){let g=st(t,"fd",String(d));await xd(g,s[d])}return a}static async readMaterial(e){let t=st(e,py),r=st(t,"ac"),i=new Uint8Array(await Td(r)),o=[];for(let d=0;d<Pa;d++){let g=st(t,"fd",String(d)),w=await Td(g);o.push(new Uint8Array(w))}let s=st(t,"ce"),a=await Td(s),c=fy(o,i),l=hy(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=jk(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return my(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return hy(r,i).toString("utf8")}};import Ey from"fs";import Ta from"path";import Jk from"json5";import*as Ia from"fs";import*as yy from"path";function Aa(n){let e=yy.resolve(n);if(!Ia.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Ia.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Br from"fs";import*as De from"path";import{debuglog as Ur}from"util";var wy={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function Gk(n){return Object.prototype.hasOwnProperty.call(wy,n)}function Da(n){if(Gk(n))return wy[n]}var vy={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as Vk}from"url";var ka=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function Ra(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Sy(n){return n==null||n.length===0}function zk(n){return!Sy(n)}function Nd(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function qk(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function Yk(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var yn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=De.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=De.join("lib","permissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=De.join(t.sdkPath,"default","sdk-pkg.json"),a=Aa(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=De.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Br.existsSync(e))return Br.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=Vk(e);if(t.includes("dist")){let s=De.dirname(t),a=De.dirname(s);return De.join(a,"src","resources")}let r=De.dirname(t),i=De.dirname(r),o=De.dirname(i);return De.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Ur("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:Ra(i)?Object.values(i):[]).filter(Ra).map(a=>new ka(a));s.forEach(a=>{let c=a.permissionInsteadName;zk(c)&&(a.permissionInsteadName=Da(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Ur(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!Ra(o))return;let s=o,a=Nd(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Sy(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Nd(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Nd(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:qk(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new ka;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=Yk(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=De.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Br.existsSync(t))return;let r;try{r=Br.readFileSync(t,"utf-8")}catch(s){Ur(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!Ra(s)){Ur("json object is null");return}i=s}catch(s){Ur(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Ur("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Da(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Da(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function xa(n,e){let t=new Set,r=new Set;yn.handleSpecificAclPermissions(),yn.initAclPermission(n,e);for(let i of n.profile.modules){let o=by(i,n,e,r,Ta.join("src","main"));for(let a of o)t.add(a);let s=by(i,n,e,r,Ta.join("src","ohosTest"));for(let a of s)t.add(a)}return Kk(r),t}function Kk(n){if(n.size>0)throw new Error(vy.DUPLICATE_PERMISSION)}function by(n,e,t,r,i){let o=Zk(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let P=Xk(w,"name");P&&s.push(P)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=Ta.join(t.sdkPath,"default","sdk-pkg.json"),l=Aa(c),d=yn.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let P=Number(w.minSupportApiLevel);return Number.isFinite(P)&&P<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function Xk(n,e){let t=n[e];return typeof t=="string"?t:""}function Zk(n,e,t){let r=Ta.join(n,e.srcPath,t,"module.json5"),i=Qk(r);if(i==null)return null;let o=eT(i,"module");return o==null?null:tT(o,"requestPermissions")}function Qk(n){try{if(!Ey.existsSync(n))return null;let e=Ey.readFileSync(n,"utf-8");return Jk.parse(e)}catch{return null}}function eT(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function tT(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var Md=class{verifyStorePassword(e,t){try{let r=wn.readFileSync(e),i=Cy.asn1.fromDer(r.toString("binary"));return Cy.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=wn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new La.X509Certificate(i).fingerprint256));try{return[this.formatFp(new La.X509Certificate(wn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=wn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new La.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function rT(n){let e=wn.readFileSync(n,"utf-8"),t=iT(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Od(i["bundle-name"]),expiryDate:oT(r?.validity?.["not-after"]),cerFingerprintInProfile:sT(Od(i["development-certificate"])),deviceUdidsInProfile:aT(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:cT(r?.acls?.["allowed-acls"]),teamIdInProfile:Od(i["developer-id"])}}function iT(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function oT(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function sT(n){if(!n)return null;try{let t=new La.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function aT(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function cT(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function Od(n){return typeof n=="string"?n:null}var so=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=V.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([lT(o,a),uT(t.hdcPath)]),d=null;if(Iy(c).allExist)try{d=rT(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await dT(a,o,c.storeFile),localAclPermissions:[...xa(s,t)].sort(),hapSignTool:new Md,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Ne({force:!0})}):null}static#n(e){let t=Iy(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Ne({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=fT(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return mT(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Ne({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function lT(n,e){let[t,r,i,o]=await Promise.all([ye(n,e,"p12"),ye(n,e,"csr"),ye(n,e,"cer"),ye(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function dT(n,e,t){let r=Ay.join(n,"build-profile.json5");if(!wn.existsSync(r))return;let i;try{i=nT.parse(wn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await gn.decryptPassword(a,t)}catch{return}}async function uT(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Py(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1382
|
-
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await
|
|
1383
|
-
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function
|
|
1384
|
-
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await
|
|
1385
|
-
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function vT(n,e){let{stdout:t}=await Fd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return ST(t)}function ST(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import Bn from"fs";import{createHash as ET}from"crypto";import{debuglog as Mt}from"util";import{Buffer as Oy}from"buffer";import{createPublicKey as bT,X509Certificate as jd}from"crypto";import{readFileSync as PT}from"fs";import Wn from"node-forge";async function My(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(v.DEVICE_LIST_EMPTY);let d=`${K.BASE_URL}${K.PROVISION_ADD_TEST_PATH}`,g=CT(t,r),w=await AT(n,d,a||[],r,s,g,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Mt("add provision failed, the provision file url is null"),new Error(v.ADD_PROFILE_FAIL);let P=w.profileInfo,ne=(await TT(n,P.provisionFileUrl)).urlList,wt=w.profileInfo.id;if(ne&&ne.length>0){let at=await uy(t,i),_t=at.profilePath;if(!await xT(ne,_t))throw await Ny(n,wt),new Error(v.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Ny(n,wt),Bn.existsSync(at.certPath)&&Bn.existsSync(_t)&&Bn.existsSync(at.p12Path)){let Vy=Bn.readFileSync(at.certPath,"utf8"),zy=Bn.readFileSync(_t,"utf8");return LT(zy,Vy,at.p12Path,c,l)||kT(_t),_t}}throw new Error(v.ADD_PROFILE_FAIL)}function CT(n,e){let t=n?`${n}_`:"";return`${IT(`${t}${e}_${e}`)}`}function IT(n){return ET("sha256").update(n).digest("hex").substring(0,16)}async function AT(n,e,t,r,i,o,s){DT(r);let a=$d(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await L.postAllowFailure(e,{headers:a,params:c});if(!l)throw Mt("add provision failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw Hd(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Mt(`add provision fail: ${l.data}`),RT(l.data,o),new Error(d.ret?.msg||v.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function Hd(n,e,t){return n===it.FORBIDDEN?e===ue.OPENPROXY_BLOCKED_URL?new Error(v.ERR_CERT_NETWORK_ERROR):new Error(v.ERR_FORBIDDEN):n===it.UNAUTHORIZED?new Error(v.ERR_UNAUTHORIZED):t.includes(ue.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(v.TEST_PROVISION_EXCEEDS_LIMIT):new Error(v.ADD_PROFILE_FAIL)}function DT(n){if(!n||n.trim().length===0)throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!Ae.BUNDLE_NAME_REGEX.test(n))throw new Error(v.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function RT(n,e){if(n.includes(ue.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(v.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ue.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(v.PROFILE_NAME_REPEAT)}async function Ny(n,e){if(!e||e.trim().length===0)return;let t=`${K.BASE_URL}${K.PROVISION_DELETE_PATH}?id=${e}`,r=await L.deleteAllowFailure(t,{headers:$d(n)});if(r.statusCode!==200)throw Hd(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Mt(`delete provision failed: ${r.data}`)}function kT(...n){for(let e of n)try{Bn.existsSync(e)&&Bn.unlinkSync(e)}catch(t){Mt(`delete local sign file error: ${t.message}`)}}async function TT(n,e){let t=`${K.BASE_URL}${K.CERT_DOWNLOAD_URL_PATH}`,r=$d(n),i={sourceUrls:e},o=await L.postAllowFailure(t,{headers:r,params:i});if(!o)throw Mt("get download list failed: response is null"),new Error(v.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw Hd(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Mt("download: The application does not exist"),new Error(s.ret?.msg||v.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function xT(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await ro(t,e),!0}function LT(n,e,t,r,i){return NT(n,e),r=r||Ae.TARGET_FRIENDLY_NAME,i=i||"",OT(e,t,r,i),!0}function NT(n,e){if(e.lastIndexOf(Ae.CERT_BEGIN_HEADER)<0)throw new Error(v.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(Ae.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function OT(n,e,t,r){let i=n.matchAll(Ae.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=MT(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let P=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${P}`),new Error(v.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(v.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(v.CERTIFICATE_HAS_EXPIRED);if(!FT(e,t,r,o))throw new Error(v.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function MT(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new jd(t);let r=Oy.from(t,"base64");return new jd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function _T(n){if(n.cert){let e=Wn.pki.publicKeyToPem(n.cert.publicKey);return bT(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Wn.asn1.toDer(n.asn1).getBytes(),t=Oy.from(e,"binary");return new jd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Mt(`Failed to parse cert from asn1: ${e}`),null}return null}function FT(n,e,t,r){try{let i=PT(n),o=Wn.asn1.fromDer(Wn.util.createBuffer(i)),c=Wn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Wn.pki.oids.certBag})[Wn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=_T(l);if(!g)continue;if(r.some(P=>{let O=P.publicKey.export({type:"spki",format:"der"});return g.equals(O)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Mt(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function $d(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Fy="https://developer.huawei.com",jT={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},HT="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function $T(n){let e=jT[n];return e?`${Fy}${e}`:void 0}function UT(){return`${Fy}${HT}`}var BT={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function _y(n,e){return(BT[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function WT(n){return Array.from(n).join(", ")}function jy(n,e){if(n.size===0)return;let t=yn.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=$T(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;o.add(`${w} (${g.permissionHelpUrlKey})`)}let s=UT(),a=_y("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=_y("acl.permissions.warn",[WT(i),l,c]);console.log(d)}var Oa=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=V.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(ee.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:ee.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import GT from"fs";import Hy from"path";var Ma=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=Hy.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!GT.existsSync(r)){let i=Hy.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var _a=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await ie.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await ie.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(ee.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(ee.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(ee.TEAM_INFO_FAILED);try{if((await Yt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(ee.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(ee.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(ee.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(ee.REALNAME_REQUIRED)):{passed:!0,message:""}:e(ee.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Yt();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(ee.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(ee.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function VT(n){try{let{teamList:e}=await Yt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function zT(n){let e=await ie.getUserInfo(),t=await ie.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await VT(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Na(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var Fa=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await zT(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await Q.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(ee.DEVICE_MISSING)):o.some(a=>Bt(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(ee.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(ee.DEVICE_DETECT_FAILED)}}};var ja=class{projectChecker=new Oa;toolchainChecker=null;authChecker=new _a;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new Ma(e),this.deviceChecker=new Fa(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(ee.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function JT(n){if(Bd.existsSync(n)){let e=Bd.readFileSync(n,"utf-8");return Uy.parse(e)}return{app:{signingConfigs:[],products:[]}}}function KT(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function XT(n){if(n.keyPwd===n.storePassword){let r=await gn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await gn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await gn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function ZT(n,e,t){let r=$y.join(n,"build-profile.json5"),i=JT(r);KT(i);let o=t??"default",{keyPassword:s,storePassword:a}=await XT(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ot.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Bd.writeFileSync(r,Uy.stringify(i,null,2),"utf-8")}async function QT(n){let e=await ie.getUserInfo(),t=await ie.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function ex(n){let e=n.product||"default";await new ja().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await QT(n),i=await I.new(),{shouldRegenerate:o}=await so.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Ud("Signature generation completed successfully."));return}await tx(n,r,i),console.log(Ud("Signature generation completed successfully."))}async function tx(n,e,t){let r=await Rd(e,n.product),i=nx(n,e,r,t);i.allDeviceIds=await Ry(e,t.hdcPath),await My(e,i);let o=V.discover(process.cwd()).rootDir;await ZT(o,r,n.product??"default"),console.log(Ud(`Signing config written to ${$y.join(o,"build-profile.json5")}`))}function nx(n,e,t,r){let i=process.cwd(),o=V.discover(i),s=xa(o,r);return jy(s,o),{productName:n.product||"default",bundleName:o.getBundleName(),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var By=new qT("signature").description("Generate application signature.");By.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{try{await ex(n)}catch(e){console.error(YT(e.message)),process.exit(1)}});var Wy=By;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";rx();te.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.11");te.addCommand(ku);te.addCommand(tp);te.addCommand(lp);te.addCommand(Pp);te.addCommand(Kp);te.addCommand(Sf);te.addCommand(zf);te.addCommand(Jf);te.addCommand(sm);te.addCommand(mm);te.addCommand(Nm);te.addCommand(tg);te.addCommand(Ag);te.addCommand(ry);te.addCommand(Wy);var Wd=process.argv.slice(2);Wd.length>=2&&Wd[Wd.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function ox(n){let e=n;for(;e.parent&&e.parent!==te;)e=e.parent;return e}var sx=new Set(["update","auth","serve"]);te.hook("preAction",async(n,e)=>{let t=ox(e),r=er();if(t.name()==="update")return;let i=new zt(Gy.join(ut(),"update")),o=Vt();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||sx.has(t.name())||await I.checkVersion()});te.hook("postAction",async(n,e)=>{if(process.exitCode||er()!=="off")return;await new ri(e).checkAndNotify()});te.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(ix(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|
|
1379
|
+
${i.stderr}`:""));throw i.stdout&&(o.stdout=i.stdout),o}}function tk(n,e){if(!HR.includes(e.format))throw new LR(`--format must be default, csv, or json (console: default|json, file: default|csv|json). got "${e.format}"`);if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function nk(n,e){let t=[];if(n.sourceVersion&&!e.includes(n.sourceVersion)&&t.push(`--source-version "${n.sourceVersion}"`),n.targetVersion&&!e.includes(n.targetVersion)&&t.push(`--target-version "${n.targetVersion}"`),t.length>0){let r=t.length>1?"are":"is";throw new Error(`${t.join(" and ")} ${r} not in the available SDK version list.
|
|
1380
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),i=e.indexOf(n.targetVersion);if(r>=i)throw new Error(`--target-version "${n.targetVersion}" must be later than --source-version "${n.sourceVersion}". Run \`devecocli compat versions\` to see the available order.`)}}function rk(n,e,t,r,i){i==="none"&&(t==="json"?XR(n,r):KR(n,r)),JR(n,e)}function ik(n,e){let t=G.dirname(n),r=G.basename(n),i=e.slice(1).map(o=>o.startsWith("--")?o:`"${o}"`).join(" ");m(de(`[compat:check] command: cd "${t}" && node "${r}" ${i}`))}function ok(n){try{_R(n),m(de(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(de(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var sk=[".csv",".json"];function ak(n){return sk.includes(n.toLowerCase())}function ck(n,e){if(!n)return{kind:"none"};let t=G.extname(n).toLowerCase();if(!ak(t))return{kind:"dir",dirPath:G.resolve(n)};if(t===".csv"&&!(e==="default"||e==="csv")||t===".json"&&e!=="json")throw new Error(`The --output-path file extension '${t}' does not match --format ${e}. Use --format ${t===".json"?"json":"default"}, or rename the file.`);return{kind:"file",filePath:G.resolve(n),ext:t}}function lk(n){if(n.kind==="file"){if(Sa(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=G.dirname(n.filePath);if(!Sa(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!Sa(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function iy(n){return JSON.stringify({records:n,count:n.length},null,2)+`
|
|
1381
|
+
`}function dk(n,e,t,r){r===".csv"?Qg(n,t):ey(t,iy(e),"utf8"),m(de(`[compat:check] saved report: "${t}"`))}function uk(n,e,t,r){if(r==="json"){let o=G.basename(n,".csv"),s=G.join(t,`${o}.json`);return ey(s,iy(e),"utf8"),m(de(`[compat:check] saved report: "${s}"`)),s}let i=G.join(t,G.basename(n));return Qg(n,i),m(de(`[compat:check] saved report: "${i}"`)),i}async function pk(n,e){let t=new Me(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(i){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+i.message,{cause:i})}}async function fk(n,e){tk(n,e);let t=V.discover(process.cwd());e.modules&&e.modules.length>0&&UR(t,e.modules),n.length>0&&BR(n);let r=await A.new(),{apiChangeDir:i,scriptPath:o}=r.getApiscanPaths();m(de(`[compat:check] script: "${o}"`));let s=ny(i);nk(e,s),e.outputPath&&m(de(`[compat:check] outputPath: "${e.outputPath}"`));let a=ck(e.outputPath,e.format);return m(de(`[compat:check] outputTarget: ${a.kind}`)),lk(a),{project:t,scriptPath:o,target:a,toolProvider:r}}async function oy(n,e){let{project:t,scriptPath:r,target:i,toolProvider:o}=await fk(n,e),s=jR({text:"Running compatibility check...",color:"cyan"}).start();try{await pk(o,e);let a=QR(r,n,t,e);ik(r,a);let c=await ek(o,a),l=YR(c,wd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(de(`[compat:check] tmp csv: "${l}"`));let d=qR(l),g=null;if(i.kind==="file")dk(l,d,i.filePath,i.ext),g=i.filePath;else if(i.kind==="dir")g=uk(l,d,i.dirPath,e.format);else if(i.kind!=="none")throw new Error(`Unexpected output target kind: ${i.kind}`);ok(l),s.stop(),rk(d,g,e.format,e.limit,i.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}function hk(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new mk(`--limit must be a positive integer (got "${n}")`);return e}function gk(){let n=process.argv;for(let e=0;e<n.length;e++){if(n[e]==="--format"&&e+1<n.length)return n[e+1];if(n[e].startsWith("--format="))return n[e].slice(9)}}var vd=new sy("compat").description("Compatibility checking utilities.");vd.description("Check source code compatibility against a target SDK version. By default, performs a project-level scan; pass positional `files...` for file-level scanning; pass `--modules` for module-level scanning.").arguments("[files...]").option("--source-version <version>","Current project SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--target-version <version>","Target SDK version (required; use `compat versions` to list available versions). On zsh, quote the value because version strings contain parentheses; run `compat versions` first to copy a real example.").option("--modules <modules...>","Modules to check (default: all modules in the project). Mutually exclusive with positional file arguments.").option("--format <format>",'Output format: "json" or "default" (text) for console; "csv", "json", or "default" for file output (--output-path). "csv" requires --output-path.',"default").option("--output-path <path>","Directory to write the detailed report CSV to (default: ./compat-output)").option("--limit <num>","Maximum number of change records to display (default: 100)",hk,100).action(async(n,e)=>{await oy(n,e)});vd.command("versions").description("List all available target SDK versions for compatibility checking").option("--format <format>","Output format: default or json").action(async()=>{await ry(gk())});var yk=new sy("check").description("Run DevEco project checks").addCommand(vd).addCommand(gd()),ay=yk;import{Command as rx}from"commander";import{green as Bd,red as ix}from"colorette";import Wd from"fs";import Gy from"path";import Vy from"json5";import{readFileSync as Gk}from"fs";import{join as wk}from"path";var K={BASE_URL:"https://connect-api.cloud.huawei.com",CERT_LIST_PATH:"/api/cps/harmony-cert-manage/v1/cert/list",CERT_DELETE_PATH:"/api/cps/harmony-cert-manage/v1/cert/delete",CERT_ADD_PATH:"/api/cps/harmony-cert-manage/v1/cert/add",CERT_DOWNLOAD_URL_PATH:"/api/amis/app-manage/v1/objects/url/reapply",DEVICE_ADD_PATH:"/api/cps/device-manage/v1/device/add",DEVICE_LIST_PATH:"/api/cps/device-manage/v1/device/list",PROVISION_ADD_REAL_PATH:"/api/cps/provision-manage/v1/ide/real/provision/add",PROVISION_ADD_TEST_PATH:"/api/cps/provision-manage/v1/ide/test/provision/add",PROVISION_DELETE_PATH:"/api/cps/provision-manage/v1/provision/delete"},De={CERT_NAME_PREFIX:"auto_debug_",CERT_TYPE_DEBUG:"1",TEAM_ID_INVALID_CHARS:/[\\/.:]/g,CERT_PATTERN:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/,TARGET_FRIENDLY_NAME:"debugKey",CERTIFICATE_PATTERN_GLOBAL:/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,BUNDLE_NAME_REGEX:/^[a-zA-Z][a-zA-Z0-9._-]*$/,CERT_BEGIN_HEADER:"-----BEGIN CERTIFICATE-----",CERT_SAVE_DIR:wk(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ue={SUCCESS_MARKER:'"code":0',SQUARE_BRACKETS:"[]",OPENPROXY_BLOCKED_URL:"Openproxy_Blocked_URL_list",CERT_LIMIT_CODE:"205389872",USER_NOT_HARMONY_CODE:"205389904",DEVICE_EXCEEDS_LIMIT_CODE:"205389859",DEVICE_NAME_REPEAT_CODE:"205389857",PROVISION_EXCEEDS_LIMIT_CODE:"205389938",PROVISION_NAME_REPEAT_CODE:"205389830"},it={FORBIDDEN:403,UNAUTHORIZED:401},S={ERR_FORBIDDEN:"You do not have AppGallery Connect permissions for the current team. Request access from the team administrator or switch to a team where you have permissions.",ERR_UNAUTHORIZED:"Invalid AccessToken. Sign in and try again.",ERR_CERT_LIMIT_REACHED:"The number of certificates has reached the limit. Delete some certificates and try again.",ERR_CERT_NETWORK_ERROR:"Ensure the external network connection is available before downloading the certificate.",ERR_CERT_INVALIDATE:"The downloaded .cer file is invalid. Try again.",ERR_DOWNLOAD_CER:"Failed to download the certificate file. Check the following configurations: Network connection, HTTP Proxy, etc.",ERR_USER_NOT_HARMONY:"The user is not in harmony allow list, please grant the permission",ERR_READ_CSR:"Failed to read the .csr file, please try again later",ERROR_WHILE_ADD_DEVICE:"Failed to add the device, please try again.",DEVICE_LIMIT_REACHED:"The number of devices has reached the limit. Delete some unused devices and try again.",DEVICE_NAME_REPEAT:"Duplicate device name, please try again.",DEVICE_LIST_EMPTY:"No devices available.",ADD_PROFILE_FAIL:"Failed to add the profile, please try again.",NO_AGC_PERMISSION:"You do not have the AppGallery Connect permission with the current team. Apply for the permission form the team administrator, or switch to a team with which you already have the permission.",ERROR_WHILE_DOWNLOAD_PROFILE:"Failed to download the profile, please try again.",PROFILE_NAME_REPEAT:"The profile name already exists in the AGC.",ERROR_WHILE_PARSE_PROFILE:"Failed to parse the profile, please try again.",TEST_PROVISION_EXCEEDS_LIMIT:"Provision number exceeds limit.",CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT:"The certificate application file is inconsistent with the file in profile, please try again.",CERTIFICATE_HAS_EXPIRED:"The signature does not take effect or has expired. It may be the current system time is inaccurate, please calibrate the system time and sign again.",ERROR_SIGN_BUNDLE_NAME_VALIDATE:"The bundle name contains 7 to 128 characters, including only letters, digits, and underscores (_). It must be start with a letter and contain at least three segments separated by periods (.), each of the segments ending with a digit or letter."},Q={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Ea(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Sd(n){let e=n.replace(De.TEAM_ID_INVALID_CHARS,"");return`${De.CERT_NAME_PREFIX}${e}.cer`}function $r(n,e,t){if(n===it.FORBIDDEN)return e===ue.OPENPROXY_BLOCKED_URL?new Error(S.ERR_CERT_NETWORK_ERROR):new Error(S.ERR_FORBIDDEN);if(n===it.UNAUTHORIZED)return new Error(S.ERR_UNAUTHORIZED);if(t.includes(ue.USER_NOT_HARMONY_CODE))return new Error(S.ERR_USER_NOT_HARMONY);if(t.includes(ue.CERT_LIMIT_CODE))return new Error(S.ERR_CERT_LIMIT_REACHED);let r=vk(t);return new Error(r??S.ERR_DOWNLOAD_CER)}function vk(n){let e=cy(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?cy(t):t;if(r&&typeof r=="object"){let i=r.msg;if(typeof i=="string"&&i.trim()!=="")return i}return null}function cy(n){try{return JSON.parse(n)}catch{return null}}function Ed(n){return JSON.parse(n)}async function ly(n){let e=`${K.BASE_URL}${K.CERT_LIST_PATH}`,t=await N.postAllowFailure(e,{headers:Ea(n)});if(t.statusCode!==200)throw $r(t.statusCode,t.statusText,t.data);return Ed(t.data)?.certList??[]}async function ba(n,e){return(await ly(n)).find(r=>r.certName===e)??null}async function bd(n,e){let t=`${K.BASE_URL}${K.CERT_DELETE_PATH}`,r=await N.deleteAllowFailure(t,{headers:Ea(n),params:{certIds:[e]}});if(r.statusCode!==200)throw $r(r.statusCode,r.statusText,r.data);return Ed(r.data)?.ret?.code===0}async function Pd(n,e,t){let r=`${K.BASE_URL}${K.CERT_ADD_PATH}`,i={csr:e,certName:t,certType:De.CERT_TYPE_DEBUG},o=await N.postAllowFailure(r,{headers:Ea(n),params:i});if(o.statusCode!==200)throw $r(o.statusCode,o.statusText,o.data);if(!o.data.includes(ue.SUCCESS_MARKER))throw $r(void 0,o.statusText,o.data)}async function Cd(n,e){let t=`${K.BASE_URL}${K.CERT_DOWNLOAD_URL_PATH}`,r=await N.postAllowFailure(t,{headers:Ea(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw $r(r.statusCode,r.statusText,r.data);return Ed(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as Sk,writeFileSync as Ek,existsSync as bk}from"fs";import{dirname as Pk}from"path";async function ro(n,e){let{statusCode:t,statusText:r,buffer:i}=await N.getBinaryAllowFailure(n,{timeout:De.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===it.FORBIDDEN&&r===ue.OPENPROXY_BLOCKED_URL?new Error(S.ERR_CERT_NETWORK_ERROR):new Error(S.ERR_DOWNLOAD_CER);let o=Pk(e);bk(o)||Sk(o,{recursive:!0}),Ek(e,i)}import Uk from"fs/promises";import{readFileSync as Bk}from"fs";import Pa from"path";import py from"crypto";import Ck from"os";import io from"fs/promises";var fy={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},dy=["ECC","RSA"],uy=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Ik={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Ak=8,Id=64,Dk=/[\\:*?"<>|=-]/g,ot={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Rk(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(n.keyAlias.length>Id)throw new Error(`The length of keyAlias cannot exceed ${Id}`);if(!dy.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${dy.join(" / ")}`);let e=Ik[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function kk(n){if(!n.keyAlias.trim())throw new Error("keyAlias cannot be empty");if(!n.keystoreFile.trim())throw new Error("keystoreFile cannot be empty");if(!n.subject.trim())throw new Error("subject cannot be empty");if(!uy.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${uy.join(" / ")}`)}function Tk(n){return py.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function xk(n){let e=n?.trim()??"";return e&&e.replace(Dk,"_").slice(0,Id)||ot.productName}async function my(){let n=await A.new(),e=n.javaPath;if(!e)throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=Pa.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");try{await io.access(r)}catch(i){throw new Error(`Sign tool jar not found: ${r}`,{cause:i})}return{javaPath:e,jarPath:r}}async function Nk(n){let{javaPath:e,jarPath:t}=await my(),r=["-jar",t,fy.GENERATE_KEYPAIR,"-keyAlias",n.keyAlias,"-keyAlg",n.keyAlg,"-keySize",n.keySize,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function Lk(n){let{javaPath:e,jarPath:t}=await my(),r=["-jar",t,fy.GENERATE_CSR,"-keyAlias",n.keyAlias,"-subject",n.subject,"-signAlg",n.signAlg,"-keystoreFile",n.keystoreFile,"-keystorePwd",n.keystorePwd];n.outFile&&r.push("-outFile",n.outFile),n.keyPwd&&r.push("-keyPwd",n.keyPwd),n.pwdInputMode&&r.push("-pwdInputMode",n.pwdInputMode);let i=r.map(o=>["-keyPwd","-keystorePwd"].includes(o)?`${o} ******`:o);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",i.join(" ")),[e,...r]}async function Ok(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Rk(n);let e=await Nk(n),t=await Xr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the private key P12, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210P12\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}async function Mk(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),kk(n);let e=await Lk(n),t=await Xr(e[0],e.slice(1));if(t.exitCode!==0){let r=t.stderr||t.stdout||"Unknown tool error";throw new Error(`An error occurred while generating the CSR, exit code${t.exitCode}\uFF1A${r}`)}return f.info("\u751F\u6210CSR\u547D\u4EE4\u6267\u884C\u5B8C\u6210"),t}function _k(n=Ak){return py.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Fk(){let n=Ck.homedir();try{await io.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Pa.join(n,".ohos","config");try{await io.mkdir(e,{recursive:!0,mode:448})}catch(t){throw new Error(`Failed to create directory ${e}`,{cause:t})}return f.info(`\u7B7E\u540D\u914D\u7F6E\u76EE\u5F55\u5C31\u7EEA\uFF1A${e}`),e}async function ye(n,e,t){let r=xk(n),i=Pa.basename(e),o=Tk(e),s=`${r}_${i}_${o}=.${t}`,a=await Fk();return Pa.join(a,s)}function jk(n){let e;try{e=V.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function Hk(n){try{await io.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function $k(n){try{await io.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function Ad(n,e,t){let r=process.cwd(),i=jk(r);await Hk(i),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${i}`);let o=_k(),s=await ye(n??"",i,"p12"),a=await ye(n??"",i,"csr");return console.log("Start generating p12"),await Ok({keyAlias:e?.keyAlias??ot.keyAlias,keyPwd:o,keyAlg:e?.keyAlg??ot.keyAlg,keySize:e?.keySize??ot.keySize,keystoreFile:s,keystorePwd:o}),await $k(s),console.log("Start generating csr"),await Mk({subject:t?.subject??ot.csrSubject,outFile:a,keyAlias:t?.keyAlias??ot.keyAlias,keyPwd:o,signAlg:t?.signAlg??ot.signAlg,keystoreFile:s,keystorePwd:o}),{p12FilePath:s,csrFilePath:a,keyPwd:o,keyAlias:e?.keyAlias??ot.keyAlias}}var Wk=["p12","cer","csr","p7b"];async function Dd(n,e){for(let t of Wk){let r=await ye(n,e,t);await Uk.rm(r,{force:!0})}}function Rd(n){let e;try{e=Bk(n,"utf-8")}catch{throw new Error(S.ERR_CERT_INVALIDATE)}if(!De.CERT_PATTERN.test(e))throw new Error(S.ERR_CERT_INVALIDATE)}async function hy(n,e){return{certPath:await ye(n,e,"cer"),csrPath:await ye(n,e,"csr"),p12Path:await ye(n,e,"p12"),profilePath:await ye(n,e,"p7b")}}async function kd(n,e){let t=e??"",r=V.discover(process.cwd()).rootDir;await Dd(t,r);let i=Sd(n.teamId),o=await ba(n,i);if(o&&!await bd(n,o.id))throw new Error(S.ERR_DOWNLOAD_CER);let s=await Ad(e),a;try{a=Gk(s.csrFilePath,"utf-8")}catch{throw new Error(S.ERR_READ_CSR)}console.log("Start generating certificate"),await Pd(n,a,i);let c=await ba(n,i);if(!c)throw new Error(S.ERR_DOWNLOAD_CER);let l=await Cd(n,c.certObjectId);if(!l)throw new Error(S.ERR_DOWNLOAD_CER);let d=await ye(t,r,"cer");await ro(l,d),Rd(d);let g=await ye(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:g,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import La from"crypto";import wn from"fs";import*as Ty from"path";import pT from"json5";import{execa as Dy}from"execa";import Ry from"node-forge";import{createCipheriv as Vk,createDecipheriv as zk,pbkdf2Sync as qk,randomBytes as Ld}from"crypto";import{promises as Un}from"fs";import{dirname as Yk,join as st}from"path";var Ca=3,oo=16,Jk=1e4,gy="material",Kk=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Sy="aes-128-gcm",$n=12,Ia=16,hn=4;function Td(n){return new Uint8Array(Ld(n))}function Xk(n){return Ld(n).toString("hex")}function Zk(...n){if(n.length===0)return new Uint8Array(0);let e=n[0].length,t=new Uint8Array(e);for(let r=0;r<e;r++){let i=0;for(let o of n)i^=o[r];t[r]=i}return t}function yy(n,e,t=Jk,r=oo){let i=[...n,Kk],o=Zk(...i),s=Buffer.from(o).toString("utf8"),a=Buffer.from(s,"utf8"),c=qk(a,e,t,r,"sha256");return new Uint8Array(c)}function wy(n,e){let t=Ld($n),r=Vk(Sy,n,t),i=Buffer.concat([r.update(e),r.final()]),o=r.getAuthTag(),s=Buffer.concat([i,o]),a=s.length,c=Buffer.alloc(hn+$n+s.length);return c.writeUInt32BE(a,0),t.copy(c,hn),s.copy(c,hn+$n),c}function vy(n,e){if(e.length<hn+$n+Ia)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(hn,hn+$n),i=e.subarray(hn+$n,hn+$n+t);if(i.length<Ia)throw new Error("Ciphertext too short for auth tag");let o=i.subarray(0,i.length-Ia),s=i.subarray(i.length-Ia),a=zk(Sy,n,r);return a.setAuthTag(s),Buffer.concat([a.update(o),a.final()])}async function Qk(n){try{await Un.rm(n,{recursive:!0,force:!0})}catch{}}async function xd(n){let e=await Un.readdir(n),t=e.filter(r=>r!==".DS_Store");if(t.length!==1)throw new Error(`Expected exactly 1 file in ${n}, but found ${t.length} (filtered from ${e.length})`);return Un.readFile(st(n,t[0]))}async function Nd(n,e){let t=Xk(oo),r=st(n,t);return await Un.writeFile(r,e),t}var gn=class{static async generateMaterial(e){let t=st(e,gy);await Qk(t);let r=st(t,"ac"),i=st(t,"ce");await Un.mkdir(r,{recursive:!0}),await Un.mkdir(i,{recursive:!0});for(let d=0;d<Ca;d++)await Un.mkdir(st(t,"fd",String(d)),{recursive:!0});let o=Td(oo),s=[];for(let d=0;d<Ca;d++)s.push(Td(oo));let a=Td(oo),c=yy(s,o),l=wy(c,a);await Nd(r,o),await Nd(i,l);for(let d=0;d<Ca;d++){let g=st(t,"fd",String(d));await Nd(g,s[d])}return a}static async readMaterial(e){let t=st(e,gy),r=st(t,"ac"),i=new Uint8Array(await xd(r)),o=[];for(let d=0;d<Ca;d++){let g=st(t,"fd",String(d)),w=await xd(g);o.push(new Uint8Array(w))}let s=st(t,"ce"),a=await xd(s),c=yy(o,i),l=vy(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=Yk(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),i=Buffer.from(e,"utf8");return wy(r,i).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),i=Buffer.from(e,"hex");return vy(r,i).toString("utf8")}};import Iy from"fs";import xa from"path";import oT from"json5";import*as Aa from"fs";import*as Ey from"path";function Da(n){let e=Ey.resolve(n);if(!Aa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Aa.readFileSync(e,"utf-8")}catch(s){throw new Error(`Failed to read SDK info file: ${e}`,{cause:s})}let r;try{r=JSON.parse(t)}catch(s){throw new Error(`Invalid JSON in SDK info file: ${e}`,{cause:s})}let i=r?.data?.apiVersion;if(i==null||i==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let o=Number(i);if(!Number.isFinite(o))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(i)}`);return o}import*as Br from"fs";import*as Re from"path";import{debuglog as Ur}from"util";var by={"acl.SYSTEM_FLOAT_WINDOW.instead.name":"PiPWindow","acl.READ_CONTACTS.instead.name":"contact.selectContacts","acl.READ_IMAGEVIDEO.instead.name":"PhotoViewPicker","acl.WRITE_IMAGEVIDEO.instead.name":"SaveButton","acl.READ_AUDIO.instead.name":"AudioViewPicker","acl.WRITE_AUDIO.instead.name":"AudioViewPicker","acl.READ_PASTEBOARD.instead.name":"PasteButton"};function eT(n){return Object.prototype.hasOwnProperty.call(by,n)}function Ra(n){if(eT(n))return by[n]}var Py={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as tT}from"url";var Ta=class{permissionName;permissionDisplayName;minSupportApiLevel;permissionInsteadName;permissionHelpUrlKey;constructor(e={}){this.permissionName=e.permissionName??"",this.permissionDisplayName=e.permissionDisplayName??"",this.minSupportApiLevel=e.minSupportApiLevel??"",this.permissionInsteadName=e.permissionInsteadName,this.permissionHelpUrlKey=e.permissionHelpUrlKey}};function ka(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Cy(n){return n==null||n.length===0}function nT(n){return!Cy(n)}function Od(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function rT(n,e){let t=n[e];if(typeof t=="boolean")return t;if(typeof t=="number")return t!==0;if(typeof t=="string"){let r=t.trim().toLowerCase();return r==="true"||r==="1"}return!1}function iT(n,e){let t=n[e];if(typeof t=="number")return Math.trunc(t);if(typeof t=="string"){let r=Number.parseInt(t,10);return Number.isNaN(r)?0:r}return 0}var yn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=Re.join("aclPermission","aclPermissionsInfo.json");static ACL_HAVE_INSTEAD_NAME=new Set(["ohos.permission.SYSTEM_FLOAT_WINDOW","ohos.permission.READ_CONTACTS","ohos.permission.READ_IMAGEVIDEO","ohos.permission.WRITE_IMAGEVIDEO","ohos.permission.READ_AUDIO","ohos.permission.WRITE_AUDIO","ohos.permission.READ_PASTEBOARD"]);static ACL_AVAILABLE_LEVEL_VALUE="system_basic";static ACL_AVAILABLE_TYPE_VALUE="NORMAL";static ACL_AVAILABLE_LEVEL_KEY="availableLevel";static ACL_AVAILABLE_TYPE_KEY="availableType";static ACL_PROVISION_ENABLE_KEY="provisionEnable";static ACL_NAME_KEY="name";static ACL_CONFIG_PREFIX="acl.";static ACL_INSTEAD_NAME_SUFFIX=".instead.name";static ACL_HELP_URL_KEY_SUFFIX=".help.key";static ACL_DEFINE_PERMISSION_KEY="definePermissions";static ACL_SINCE_KEY="since";static PERMISSION_DEFINITIONS_RELATIVE_PATH=Re.join("lib","PermissionDefinitions.json");static INCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.FILE_ACCESS_PERSIST","ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY","ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY"]);static EXCLUDE_ACL_PERMISSIONS=new Set(["ohos.permission.READ_DOCUMENT","ohos.permission.WRITE_DOCUMENT"]);static handleSpecificAclPermissions(){this.addAclWhiteList(this.INCLUDE_ACL_PERMISSIONS),this.addAclBlackList(this.EXCLUDE_ACL_PERMISSIONS)}static aclPermissionInfoMap=new Map;static aclPermissionNamesMap=new Map;static aclWhiteList=new Set;static aclBlackList=new Set;static builtInConfigTextLoader;static initAclPermission(e,t){let r=e.rootDir,i=this.getOrCreateSet(this.aclPermissionNamesMap,r),o=this.getOrCreateSet(this.aclPermissionInfoMap,r);i.clear(),o.clear();let s=Re.join(t.sdkPath,"default","sdk-pkg.json"),a=Da(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(i,o):this.initAclPermissionFromSDK(t,i,o)}static getAclPermissionInfos(e){return this.aclPermissionInfoMap.get(e.rootDir)??new Set}static getAclPermissionNames(e){return this.aclPermissionNamesMap.get(e.rootDir)??new Set}static addAclWhiteList(e){for(let t of e)this.aclWhiteList.add(t)}static addAclBlackList(e){for(let t of e)this.aclBlackList.add(t)}static getOrCreateSet(e,t){let r=e.get(t);return r||(r=new Set,e.set(t,r)),r}static readBuiltInConfigText(){if(this.builtInConfigTextLoader)return this.builtInConfigTextLoader();let e=Re.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(Br.existsSync(e))return Br.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=tT(e);if(t.includes("dist")){let s=Re.dirname(t),a=Re.dirname(s);return Re.join(a,"src","resources")}let r=Re.dirname(t),i=Re.dirname(r),o=Re.dirname(i);return Re.join(o,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{Ur("read builtin acl permission failed.");return}if(r!==void 0)try{let i=JSON.parse(r),s=(Array.isArray(i)?i:ka(i)?Object.values(i):[]).filter(ka).map(a=>new Ta(a));s.forEach(a=>{let c=a.permissionInsteadName;nT(c)&&(a.permissionInsteadName=Ra(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(i){Ur(`failed to parse aclPermissionsInfo.json: ${i}`)}}static initAclPermissionFromSDK(e,t,r){let i=this.parsePermissionDefinitionFile(e);i&&i.forEach(o=>{if(!ka(o))return;let s=o,a=Od(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(Cy(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||Od(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||Od(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:rT(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let i=new Ta;i.permissionName=t;let o=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;i.permissionDisplayName=o;let s=iT(r,this.ACL_SINCE_KEY);i.minSupportApiLevel=String(s),this.handleInsteadName(i,o),e.add(i)}static parsePermissionDefinitionFile(e){let t=Re.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!Br.existsSync(t))return;let r;try{r=Br.readFileSync(t,"utf-8")}catch(s){Ur(`failed to load permissionDefinitions.json: ${s}`);return}let i;try{let s=JSON.parse(r);if(!ka(s)){Ur("json object is null");return}i=s}catch(s){Ur(`failed to parse permissionDefinitions.json: ${s}`);return}let o=i[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(o)){Ur("definePermissions is not an array");return}return o}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=Ra(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=Ra(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function Na(n,e){let t=new Set,r=new Set;yn.handleSpecificAclPermissions(),yn.initAclPermission(n,e);for(let i of n.profile.modules){let o=Ay(i,n,e,r,xa.join("src","main"));for(let a of o)t.add(a);let s=Ay(i,n,e,r,xa.join("src","ohosTest"));for(let a of s)t.add(a)}return sT(r),t}function sT(n){if(n.size>0)throw new Error(Py.DUPLICATE_PERMISSION)}function Ay(n,e,t,r,i){let o=cT(e.rootDir,n,i);if(o==null)return new Set;let s=[];for(let w of o){if(typeof w!="object"||w===null)continue;let P=aT(w,"name");P&&s.push(P)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=xa.join(t.sdkPath,"default","sdk-pkg.json"),l=Da(c),d=yn.getAclPermissionInfos(e),g=new Set(Array.from(d).filter(w=>{let P=Number(w.minSupportApiLevel);return Number.isFinite(P)&&P<=l}).map(w=>w.permissionName));for(let w of Array.from(a))g.has(w)||a.delete(w);return a}function aT(n,e){let t=n[e];return typeof t=="string"?t:""}function cT(n,e,t){let r=xa.join(n,e.srcPath,t,"module.json5"),i=lT(r);if(i==null)return null;let o=dT(i,"module");return o==null?null:uT(o,"requestPermissions")}function lT(n){try{if(!Iy.existsSync(n))return null;let e=Iy.readFileSync(n,"utf-8");return oT.parse(e)}catch{return null}}function dT(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return t!=null&&typeof t=="object"&&!Array.isArray(t)?t:null}function uT(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var _d=class{verifyStorePassword(e,t){try{let r=wn.readFileSync(e),i=Ry.asn1.fromDer(r.toString("binary"));return Ry.pkcs12.pkcs12FromAsn1(i,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=wn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(i=>this.formatFp(new La.X509Certificate(i).fingerprint256));try{return[this.formatFp(new La.X509Certificate(wn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let i=wn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let o of i)try{let s=new La.X509Certificate(o);if(this.formatFp(s.fingerprint256)===t){let a=new Date(s.validTo);return isNaN(a.getTime())?null:a}}catch{}return null}formatFp(e){let t=e.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}};function fT(n){let e=wn.readFileSync(n,"utf-8"),t=mT(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let i=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:Md(i["bundle-name"]),expiryDate:hT(r?.validity?.["not-after"]),cerFingerprintInProfile:gT(Md(i["development-certificate"])),deviceUdidsInProfile:yT(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:wT(r?.acls?.["allowed-acls"]),teamIdInProfile:Md(i["developer-id"])}}function mT(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,i=!1,o=!1;for(let s=e;s<n.length;s++){let a=n[s];if(i){o?o=!1:a==="\\"?o=!0:a==='"'&&(i=!1);continue}if(a==='"')i=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function hT(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function gT(n){if(!n)return null;try{let t=new La.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function yT(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)if(typeof t=="string"){let r=t.toUpperCase();e.includes(r)||e.push(r)}return e}function wT(n){if(!Array.isArray(n))return[];let e=[];for(let t of n)typeof t=="string"?e.push(t):t&&typeof t=="object"&&typeof t.name=="string"&&e.push(t.name);return[...new Set(e)].sort()}function Md(n){return typeof n=="string"?n:null}var so=class n{static async shouldRegenerate(e,t){let r=await n.#e(e,t);return n.#t(r)??n.#n(r)??n.#r(r)??n.#i(r)??n.#o(r)??n.#s(r)??n.#a(r)??n.#c(r)??n.#l(r)??n.#d(r)??await n.#u(r)??n.#p()}static async#e(e,t){let r=e.force,i=e.teamId,o=e.productName??"default",s=V.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([vT(o,a),ET(t.hdcPath)]),d=null;if(ky(c).allExist)try{d=fT(c.profileFile)}catch{}return{force:r,teamId:i,productName:o,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await ST(a,o,c.storeFile),localAclPermissions:[...Na(s,t)].sort(),hapSignTool:new _d,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:Le({force:!0})}):null}static#n(e){let t=ky(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:Le({allFilesExist:!1,missingFiles:t.missing})})}static#r(e){return(e.profileInfo?.rawContent??"").trim().length>0?null:(m("[reGenerateSign] profile content is empty"),{shouldRegenerate:!0,reason:"Profile file content is empty",checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!1})})}static#i(e){let t=e.profileInfo?.expiryDate;return!t||t>=new Date?null:(m(`[reGenerateSign] profile expired at ${t.toISOString()}`),{shouldRegenerate:!0,reason:`Profile expired at ${t.toISOString()}`,checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#o(e){let t=e.profileInfo?.bundleNameInProfile;return t&&t===e.bundleName?null:(m(`[reGenerateSign] bundleName mismatch \u2014 current=${e.bundleName}, profile=${t}`),{shouldRegenerate:!0,reason:`bundleName mismatch: current=${e.bundleName}, in profile=${t}`,checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!1})})}static#s(e){let t=e.profileInfo?.teamIdInProfile;return t&&t===e.teamId?null:(m(`[reGenerateSign] teamId mismatch \u2014 current=${e.teamId}, profile=${t}`),{shouldRegenerate:!0,reason:`teamId mismatch: current=${e.teamId}, in profile=${t}`,checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=PT(e.profileInfo?.deviceUdidsInProfile??[],e.deviceUdids);return t.allPresent?null:(m(`[reGenerateSign] missing device UDIDs: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Device UDID(s) not in profile: ${t.missing.join(", ")}`,checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return CT(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!1})})}static#l(e){let t=e.hapSignTool.getLocalCerFingerprints(e.materialPaths.cerFile),r=e.profileInfo?.cerFingerprintInProfile;return r&&t.includes(r)?null:(m("[reGenerateSign] certificate mismatch"),{shouldRegenerate:!0,reason:"Certificate mismatch between profile and local .cer file",checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!1})})}static#d(e){let t=e.profileInfo?.cerFingerprintInProfile,r=e.hapSignTool.getLocalCerExpiry(e.materialPaths.cerFile,t);return!r||r>=new Date?null:(m(`[reGenerateSign] local certificate expired at ${r.toISOString()}`),{shouldRegenerate:!0,reason:`Local certificate expired at ${r.toISOString()}`,checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!1})})}static async#u(e){return e.storePassword?e.hapSignTool.verifyStorePassword(e.materialPaths.storeFile,e.storePassword)?null:(m("[reGenerateSign] keystore password verification failed"),{shouldRegenerate:!0,reason:"Keystore password verification failed (storeFile may be corrupted or password changed)",checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})}):(m("[reGenerateSign] no stored keystore password"),{shouldRegenerate:!0,reason:"No stored keystore password available for verification",checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!1})})}static#p(){return m("[reGenerateSign] all checks passed \u2014 skip regeneration"),{shouldRegenerate:!1,reason:"",checkDetails:Le({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function vT(n,e){let[t,r,i,o]=await Promise.all([ye(n,e,"p12"),ye(n,e,"csr"),ye(n,e,"cer"),ye(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:i,profileFile:o}}async function ST(n,e,t){let r=Ty.join(n,"build-profile.json5");if(!wn.existsSync(r))return;let i;try{i=pT.parse(wn.readFileSync(r,"utf-8"))}catch{return}let a=(i?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await gn.decryptPassword(a,t)}catch{return}}async function ET(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Dy(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1382
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{m(`Executing: ${n} -t ${i} shell bm get -u`);let{stdout:o}=await Dy(n,["-t",i,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=bT(o);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${i}, skipping`)}return r}function bT(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1383
|
+
`);for(let i=0;i<t.length-1;i++)if(t[i].includes("udid of current device is")){let s=t[i+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(s)return s[0].toUpperCase()}let r=e.match(/[A-Fa-f0-9]{64}/);return r?r[0].toUpperCase():null}function ky(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)wn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function PT(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function CT(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((i,o)=>i===r[o])}function Le(n){let e={force:!1,allFilesExist:!1,missingFiles:[],profileContentNotEmpty:!1,profileNotExpired:!1,bundleNameMatched:!1,teamIdMatched:!1,allDevicesInProfile:!1,missingDeviceUdids:[],aclMatched:!1,cerMatched:!1,cerNotExpired:!1,storePasswordValid:!1};return n.force?{...e,force:!0}:{...e,...n,force:!1}}import{debuglog as Fd}from"util";import{execa as jd}from"execa";async function Ny(n,e){let t=await Oa(n);if(!t)throw new Error(S.DEVICE_LIST_EMPTY);let r=await DT(e);if(t.length===0)for(let s of r)await IT(n,s.udid,s.deviceName);else for(let s of r)await AT(n,t,s.udid,s.deviceName);let o=(await Oa(n)).map(s=>s.id);if(o.length===0)throw new Error(S.DEVICE_LIST_EMPTY);return o}async function IT(n,e,t){await My(n,e,Ly(t))}async function AT(n,e,t,r){for(let i=0;i<e.length;i++){if(t===e[i].udid)return;if(i===e.length-1){await My(n,t,Ly(r));return}}}function Ly(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function xy(n,e=1,t=100){let r=`${K.BASE_URL}${K.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,i=_y(n),o=await N.get(r,{headers:i});if(!o)throw Fd("query devices failed: response is null"),new Error(S.ERROR_WHILE_ADD_DEVICE);if(o.statusCode!==200)throw Oy(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.list)throw Fd("query devices failed: response list is null"),new Error(s.ret?.msg||S.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function Oy(n,e,t){return n===it.FORBIDDEN?e===ue.OPENPROXY_BLOCKED_URL?new Error(S.ERR_CERT_NETWORK_ERROR):new Error(S.ERR_FORBIDDEN):n===it.UNAUTHORIZED?new Error(S.ERR_UNAUTHORIZED):t.includes(ue.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(S.DEVICE_LIMIT_REACHED):new Error(S.ERROR_WHILE_ADD_DEVICE)}async function Oa(n){let t=await xy(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],i=t.total,o=Math.floor(i/100)+(i%100===0?0:1);for(let s=2;s<=o;s++){let a=await xy(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function My(n,e,t){let r=`${K.BASE_URL}${K.DEVICE_ADD_PATH}`,i=_y(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await N.postAllowFailure(r,{headers:i,params:s});if(!a)throw Fd("add device failed: response is null"),new Error(S.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Oy(a.statusCode,a.statusText,a.data);let c=a.data,l=JSON.parse(a.data);if(!l||!l.ret||l.ret.code!==0)throw c.includes(ue.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(S.DEVICE_LIMIT_REACHED):c.includes(ue.DEVICE_NAME_REPEAT_CODE)?new Error(S.DEVICE_NAME_REPEAT):new Error(S.ERROR_WHILE_ADD_DEVICE)}function _y(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function DT(n){let{stdout:e}=await jd(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let i of e.split(`
|
|
1384
|
+
`)){let o=i.trim();if(!o||o.startsWith("[Empty]"))continue;let s=o.split(/\s+/),a=s[0],c=s.length>=2?s[1]:"device";a&&!a.startsWith("[Empty]")&&c.toLowerCase()!=="unauthorized"&&t.push(a)}let r=[];for(let i of t)try{let o=await RT(i,n),s=await kT(i,n);o.length>0&&r.push({id:"",udid:o,deviceName:s})}catch{m(`Failed to get device info for ${i}, skipping`)}return r}async function RT(n,e){let{stdout:t}=await jd(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let i=r.split(`
|
|
1385
|
+
`);for(let s=0;s<i.length-1;s++)if(i[s].includes("udid of current device is")){let c=i[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let o=r.match(/[A-Fa-f0-9]{64}/);return o?o[0].toUpperCase():""}async function kT(n,e){let{stdout:t}=await jd(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return TT(t)}function TT(n){let e=n.trim();return!e||e.includes("inaccessible")?"phone":n.includes("liteWearable")?"liteWearable":n.includes("wearable")?"wearable":n.includes("tv")?"tv":"phone"}import Bn from"fs";import{createHash as xT}from"crypto";import{debuglog as Ot}from"util";import{Buffer as jy}from"buffer";import{createPublicKey as NT,X509Certificate as Hd}from"crypto";import{readFileSync as LT}from"fs";import Wn from"node-forge";async function Hy(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:i,aclPermissionList:o,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(S.DEVICE_LIST_EMPTY);let d=`${K.BASE_URL}${K.PROVISION_ADD_TEST_PATH}`,g=OT(t,r),w=await _T(n,d,a||[],r,s,g,o||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Ot("add provision failed, the provision file url is null"),new Error(S.ADD_PROFILE_FAIL);let P=w.profileInfo,te=(await $T(n,P.provisionFileUrl)).urlList,yt=w.profileInfo.id;if(te&&te.length>0){let at=await hy(t,i),Mt=at.profilePath;if(!await UT(te,Mt))throw await Fy(n,yt),new Error(S.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Fy(n,yt),Bn.existsSync(at.certPath)&&Bn.existsSync(Mt)&&Bn.existsSync(at.p12Path)){let Jy=Bn.readFileSync(at.certPath,"utf8"),Ky=Bn.readFileSync(Mt,"utf8");return BT(Ky,Jy,at.p12Path,c,l)||HT(Mt),Mt}}throw new Error(S.ADD_PROFILE_FAIL)}function OT(n,e){let t=n?`${n}_`:"";return`${MT(`${t}${e}_${e}`)}`}function MT(n){return xT("sha256").update(n).digest("hex").substring(0,16)}async function _T(n,e,t,r,i,o,s){FT(r);let a=Ud(n),c={certList:t,packageName:r,deviceList:i,provisionName:o};s.length&&(c.aclPermissionList=s);let l=await N.postAllowFailure(e,{headers:a,params:c});if(!l)throw Ot("add provision failed: response is null"),new Error(S.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw $d(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Ot(`add provision fail: ${l.data}`),jT(l.data,o),new Error(d.ret?.msg||S.ADD_PROFILE_FAIL);let g=d.provisionFileUrl;return{profileInfo:{id:d.id,name:o,provisionFileUrl:g}}}function $d(n,e,t){return n===it.FORBIDDEN?e===ue.OPENPROXY_BLOCKED_URL?new Error(S.ERR_CERT_NETWORK_ERROR):new Error(S.ERR_FORBIDDEN):n===it.UNAUTHORIZED?new Error(S.ERR_UNAUTHORIZED):t.includes(ue.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(S.TEST_PROVISION_EXCEEDS_LIMIT):new Error(S.ADD_PROFILE_FAIL)}function FT(n){if(!n||n.trim().length===0)throw new Error(S.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!De.BUNDLE_NAME_REGEX.test(n))throw new Error(S.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function jT(n,e){if(n.includes(ue.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(S.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ue.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(S.PROFILE_NAME_REPEAT)}async function Fy(n,e){if(!e||e.trim().length===0)return;let t=`${K.BASE_URL}${K.PROVISION_DELETE_PATH}?id=${e}`,r=await N.deleteAllowFailure(t,{headers:Ud(n)});if(r.statusCode!==200)throw $d(r.statusCode,r.statusText,r.data);let i=JSON.parse(r.data);(!i||!i.ret||i.ret.code!==0)&&Ot(`delete provision failed: ${r.data}`)}function HT(...n){for(let e of n)try{Bn.existsSync(e)&&Bn.unlinkSync(e)}catch(t){Ot(`delete local sign file error: ${t.message}`)}}async function $T(n,e){let t=`${K.BASE_URL}${K.CERT_DOWNLOAD_URL_PATH}`,r=Ud(n),i={sourceUrls:e},o=await N.postAllowFailure(t,{headers:r,params:i});if(!o)throw Ot("get download list failed: response is null"),new Error(S.ADD_PROFILE_FAIL);if(o.statusCode!==200)throw $d(o.statusCode,o.statusText,o.data);let s=JSON.parse(o.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Ot("download: The application does not exist"),new Error(s.ret?.msg||S.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function UT(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await ro(t,e),!0}function BT(n,e,t,r,i){return WT(n,e),r=r||De.TARGET_FRIENDLY_NAME,i=i||"",GT(e,t,r,i),!0}function WT(n,e){if(e.lastIndexOf(De.CERT_BEGIN_HEADER)<0)throw new Error(S.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(De.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(S.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function GT(n,e,t,r){let i=n.matchAll(De.CERTIFICATE_PATTERN_GLOBAL),o=[],s=new Date;for(let c of i)try{let l=c[0],d=VT(l),g=new Date(d.validFrom),w=new Date(d.validTo);if(s<g||s>w){let P=`Certificate is not valid, Valid from ${g} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${P}`),new Error(S.CERTIFICATE_HAS_EXPIRED)}o.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(S.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!o||o.length===0)throw new Error(S.CERTIFICATE_HAS_EXPIRED);if(!qT(e,t,r,o))throw new Error(S.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function VT(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new Hd(t);let r=jy.from(t,"base64");return new Hd(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function zT(n){if(n.cert){let e=Wn.pki.publicKeyToPem(n.cert.publicKey);return NT(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=Wn.asn1.toDer(n.asn1).getBytes(),t=jy.from(e,"binary");return new Hd(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Ot(`Failed to parse cert from asn1: ${e}`),null}return null}function qT(n,e,t,r){try{let i=LT(n),o=Wn.asn1.fromDer(Wn.util.createBuffer(i)),c=Wn.pkcs12.pkcs12FromAsn1(o,t).getBags({bagType:Wn.pki.oids.certBag})[Wn.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let g=zT(l);if(!g)continue;if(r.some(P=>{let O=P.publicKey.export({type:"spki",format:"der"});return g.equals(O)}))return!0}return!1}catch(i){let o=i instanceof Error?i.message:String(i);return Ot(`Failed to process P12 file: ${n}, error: ${o}`),!1}}function Ud(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Uy="https://developer.huawei.com",YT={"ohos.permission.SYSTEM_FLOAT_WINDOW":"/consumer/cn/doc/harmonyos-guides/window-pipwindow","ohos.permission.READ_CONTACTS":"/consumer/cn/doc/harmonyos-references/js-apis-contact#contactselectcontacts10","ohos.permission.READ_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E5%9B%BE%E7%89%87%E6%88%96%E8%A7%86%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_IMAGEVIDEO":"/consumer/cn/doc/harmonyos-guides/savebutton","ohos.permission.READ_AUDIO":"/consumer/cn/doc/harmonyos-guides/select-user-file#%E9%80%89%E6%8B%A9%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.WRITE_AUDIO":"/consumer/cn/doc/harmonyos-guides/save-user-file#%E4%BF%9D%E5%AD%98%E9%9F%B3%E9%A2%91%E7%B1%BB%E6%96%87%E4%BB%B6","ohos.permission.READ_PASTEBOARD":"/consumer/cn/doc/harmonyos-guides/pastebutton"},JT="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function KT(n){let e=YT[n];return e?`${Uy}${e}`:void 0}function XT(){return`${Uy}${JT}`}var ZT={"acl.can.apply.text":"Permission Application Scenarios","acl.permissions.warn":"Note: You are applying for restricted ACL permissions: {0} These permissions are subject to review together with your app release. For a faster review process, apply for the following permissions instead, if they are sufficient for your purposes: {1} {2}"};function $y(n,e){return(ZT[n]??n).replace(/\{(\d+)\}/g,(r,i)=>String(e[Number(i)]??""))}function QT(n){return Array.from(n).join(", ")}function By(n,e){if(n.size===0)return;let t=yn.getAclPermissionInfos(e),r=new Set;for(let g of t)n.has(g.permissionName)&&r.add(g);for(let g of r){let w=KT(g.permissionName);w!=null&&(g.permissionHelpUrlKey=w)}let i=new Set;for(let g of r)i.add(g.permissionDisplayName);let o=new Set;for(let g of r)if(g.permissionHelpUrlKey!=null){let w=g.permissionInsteadName??g.permissionDisplayName;o.add(`${w} (${g.permissionHelpUrlKey})`)}let s=XT(),a=$y("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=o.size>0?Array.from(o).join(", ")+".":"",d=$y("acl.permissions.warn",[QT(i),l,c]);console.log(d)}var Ma=class{_project=null;get project(){if(!this._project)throw new Error("Project not initialized. Call checkProjectDir first.");return this._project}checkProjectDir(e){try{return this._project=V.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(Q.PROJECT_DIR_MISSING)}}checkProduct(e,t){try{return this._project.validateProduct(e),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Product validation failed: ${r.message}`),t(`Product "${e}" not found.Check the product property in the build-profile.json5 file.`)}}checkBundleName(e,t){try{return this._project.getBundleName(),{passed:!0,message:""}}catch(r){return m(`[EnvCheck] BundleName check failed: ${r.message}`),t(`bundleName was not found under product "${e}".Check the bundleName configuration.`)}}checkAtomicService(){return this._project.isAtomicService()?{passed:!1,message:Q.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import ex from"fs";import Wy from"path";var _a=class{constructor(e){this.toolProvider=e}toolProvider;checkJava(e){try{return this.toolProvider.assertJava(),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Java check failed: ${t.message}`),e(`${t.message}`)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=Wy.join(t,"default","openharmony","toolchains","lib","hap-sign-tool.jar");if(!ex.existsSync(r)){let i=Wy.join("sdk","default","openharmony","toolchains","lib","hap_sign_tools.jar");return e(`hap_sign_tools.jar not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var Fa=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await re.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await re.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(Q.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(Q.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(Q.TEAM_INFO_FAILED);try{if((await Yt()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(Q.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(Q.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(Q.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(Q.REALNAME_REQUIRED)):{passed:!0,message:""}:e(Q.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let i=await Yt();if(r=e??(i.teamList.length>0?i.teamList[0].id:t.userId)??"",!i.teamList.some(s=>s.id===r)){let s=`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`;return m(`[EnvCheck] ${s}`),{passed:!1,message:s}}return{passed:!0,message:""}}catch(i){return m(`[EnvCheck] Team ID check failed: ${i.message}`),{passed:!1,message:`team-id for ${r} not found.Run devecocli auth team list to view the team to which the logged-in user belongs.`}}}async checkRegion(e){let t=await this.ensureUserInfo();return t?t.countryCode?t.countryCode!=="CN"?e(Q.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(Q.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function tx(n){try{let{teamList:e}=await Yt();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function nx(n){let e=await re.getUserInfo(),t=await re.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await tx(e.userId);if(!r)throw new Error("No team found");let i={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await Oa(i)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var ja=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await nx(t);if(r.length>0)return m(`[EnvCheck] Scenario 4 Device check: ${r.length} device(s) found in AGC cloud, skipping local device check`),{passed:!0,message:""};m("[EnvCheck] Scenario 4 Device check: no cloud devices found, falling back to local hdc");let o=await Z.from(this.toolProvider).listDevices();return o.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(Q.DEVICE_MISSING)):o.some(a=>Bt(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(Q.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(Q.DEVICE_DETECT_FAILED)}}};var Ha=class{projectChecker=new Ma;toolchainChecker=null;authChecker=new Fa;deviceChecker=null;constructor(){}async preflight(e){let t=r=>this.blockingFail(r);return!(!await this.runAuthChain(e,t)||!await this.initToolchain()||!await this.runDeviceCheck(e,t)||!await this.runProjectChecks(e,t)||!await this.runAuxChecks(e))}async runAuthChain(e,t){let r=o=>(o.passed||this.fail(o),!0),i=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let o of i)if(!r(await o()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await A.new();return this.toolchainChecker=new _a(e),this.deviceChecker=new ja(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(Q.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(i=>i.passed?!0:(this.fail(i),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=o=>o.passed?!0:(this.fail(o),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let i=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let o of i)if(!r(o()))return!1;return!0}async runAuxChecks(e){let t=r=>r.passed?!0:(this.fail(r),!1);return!e.teamId&&!t(await this.authChecker.checkTeamId(e.teamId))?!1:(await this.authChecker.checkRegion(r=>this.blockingFail(r)),!0)}blockingFail(e){return{passed:!1,message:e}}fail(e){throw m(`[EnvCheck] FAIL: ${e.message}`),new Error(e.message)}};function ox(n){if(Wd.existsSync(n)){let e=Wd.readFileSync(n,"utf-8");return Vy.parse(e)}return{app:{signingConfigs:[],products:[]}}}function sx(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function ax(n){if(n.keyPwd===n.storePassword){let r=await gn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await gn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await gn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function cx(n,e,t){let r=Gy.join(n,"build-profile.json5"),i=ox(r);sx(i);let o=t??"default",{keyPassword:s,storePassword:a}=await ax(e),c={name:o,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ot.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=i.app?.signingConfigs?.findIndex(g=>g.name===o);l!==void 0&&l>=0?i.app.signingConfigs[l]=c:i.app.signingConfigs.push(c);let d=i.app?.products?.findIndex(g=>g.name===o);d!==void 0&&d>=0?i.app.products[d].signingConfig=o:i.app.products.push({name:o,signingConfig:o}),Wd.writeFileSync(r,Vy.stringify(i,null,2),"utf-8")}async function lx(n){let e=await re.getUserInfo(),t=await re.refreshToken();if(!e||!t)throw new Error("Failed to obtain login credentials. Run `devecocli auth login` again.");return{uid:e.userId??"",teamId:n.teamId??e.userId??"",accessToken:t.accessToken??""}}async function dx(n){let e=n.product||"default";await new Ha().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await lx(n),i=await A.new(),{shouldRegenerate:o}=await so.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},i);if(!o){console.log(Bd("Signature generation completed successfully."));return}await ux(n,r,i),console.log(Bd("Signature generation completed successfully."))}async function ux(n,e,t){let r=await kd(e,n.product),i=px(n,e,r,t);i.allDeviceIds=await Ny(e,t.hdcPath),await Hy(e,i);let o=V.discover(process.cwd()).rootDir;await cx(o,r,n.product??"default"),console.log(Bd(`Signing config written to ${Gy.join(o,"build-profile.json5")}`))}function px(n,e,t,r){let i=process.cwd(),o=V.discover(i),s=Na(o,r);return By(s,o),{productName:n.product||"default",bundleName:o.getBundleName(),projectPath:o.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var zy=new rx("signature").description("Generate application signature.");zy.command("generate").description("Automatically generate signing materials and write them to the project configuration.").option("--force","Force overwrite existing local signing materials.").option("--team-id <team-id>","Specify the team ID to use.").option("--product <product>","Specify the product. The default value is default.").action(async n=>{try{await dx(n)}catch(e){console.error(ix(e.message)),process.exit(1)}});var qy=zy;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";fx();ee.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.13");ee.addCommand(Tu);ee.addCommand(np);ee.addCommand(dp);ee.addCommand(Dp);ee.addCommand(ef);ee.addCommand(Cf);ee.addCommand(Kf);ee.addCommand(Qf);ee.addCommand(dm);ee.addCommand(wm);ee.addCommand(Fm);ee.addCommand(og);ee.addCommand(Tg);ee.addCommand(ay);ee.addCommand(qy);var Gd=process.argv.slice(2);Gd.length>=2&&Gd[Gd.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);function hx(n){let e=n;for(;e.parent&&e.parent!==ee;)e=e.parent;return e}var gx=new Set(["update","auth","serve"]);ee.hook("preAction",async(n,e)=>{let t=hx(e),r=er();if(t.name()==="update")return;let i=new zt(Yy.join(ut(),"update")),o=Vt();if(r==="off"&&i.getBlockedVersions().includes(o))throw new Error(`devecocli ${o} has been disabled, run \`devecocli update\` to upgrade`);process.env.DEVECO_CLI_SKIP_VERSION_CHECK||gx.has(t.name())||await A.checkVersion()});ee.hook("postAction",async(n,e)=>{if(process.exitCode||er()!=="off")return;await new ri(e).checkAndNotify()});ee.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(mx(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|