@deveco-test/hmos-deveco-cli 0.3.0-TD.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +25 -25
- package/index.zip +0 -0
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var iv=Object.defineProperty;var sv=(n,e)=>{for(var t in e)iv(n,t,{get:e[t],enumerable:!0})};import{bootstrap as
|
|
2
|
+
var iv=Object.defineProperty;var sv=(n,e)=>{for(var t in e)iv(n,t,{get:e[t],enumerable:!0})};import{bootstrap as TL}from"global-agent";import{program as ie}from"commander";import{red as kL}from"colorette";import{Command as tS}from"commander";import{green as xc,red as Nc,yellow as Lc}from"colorette";import Z from"fs";import*as H from"path";import Ct from"json5";import*as hc from"fs";import*as we from"path";function m(n){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${n}`)}var R=class n{static ASCII_CONTROL_MAX=31;static ASCII_DELETE=127;static parsePositiveInteger(e,t="value"){let r=e.trim();if(!/^\d+$/.test(r))throw new Error(`${t} must be a positive integer`);let o=Number.parseInt(r,10);if(!Number.isInteger(o)||o<=0)throw new Error(`${t} must be a positive integer`);return o}static getLastLines(e,t){return!t||t<=0?e:e.split(/\r?\n/).slice(-t).join(`
|
|
3
3
|
`)}static parseDurationToSeconds(e,t="value"){let o=e.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)([sm])?$/);if(!o)throw new Error(`${t} must be like 30s, 5m or 2.5m (only s/m supported).`);let i=o[1];if((o[2]??"s")==="s")return n.parsePositiveInteger(i,t);if(!/^\d+(?:\.\d)?$/.test(i))throw new Error(`${t} supports a maximum of 1 decimal place for minutes (e.g. 2.5m).`);let a=Number.parseFloat(i);if(!Number.isFinite(a)||a<=0)throw new Error(`${t} must be a positive duration.`);return Math.round(a*60)}static assertRelativeTimeRange(e,t){if(e!==void 0&&t!==void 0&&e<t)throw new Error("--from must be greater than or equal to --to when both are provided (e.g. --from 30s --to 10s)")}static filterLogsByRelativeWindow(e,t,r,o=new Date){if(!t&&!r)return e;let[i,s]=n.resolveTimeBounds(t,r,o),a=e.split(/\r?\n/),c=[],l=!1;for(let d of a){let h=n.extractTimestampFromLogLine(d,o);h&&(l=n.isWithinBounds(h,i,s)),l&&c.push(d)}return c.join(`
|
|
4
4
|
`)}static resolveTimeBounds(e,t,r){let o=e?new Date(r.getTime()-e*1e3):null,i=t?new Date(r.getTime()-t*1e3):null;return o&&i?o<i?[o,i]:[i,o]:o?[o,r]:i?[null,i]:[null,null]}static isWithinBounds(e,t,r){let o=e.getTime(),i=t?Math.floor(t.getTime()/1e3)*1e3:null,s=r?Math.floor(r.getTime()/1e3)*1e3+999:null;return!(i!==null&&o<i||s!==null&&o>s)}static extractTimestampFromLogLine(e,t){let r=e.match(/(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?/);if(!r)return null;let o=t.getFullYear(),i=Number.parseInt(r[1],10)-1,s=Number.parseInt(r[2],10),a=Number.parseInt(r[3],10),c=Number.parseInt(r[4],10),l=Number.parseInt(r[5],10),d=r[6]??"0",h=Number.parseInt(d.padEnd(3,"0").slice(0,3),10),w=new Date(o,i,s,a,c,l,h);return w.getTime()>t.getTime()+1440*60*1e3&&w.setFullYear(o-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 o=0;o<t.length;o++){let i=t[o];if(!r.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed.`);if(o===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.`)}}static assertHilogToken(e,t){if(!/^[A-Za-z0-9_.:\\-]{1,64}$/.test(e))throw new Error(`Invalid ${t}: ${JSON.stringify(e)}`)}static assertHilogKeyword(e){if(e.length===0||e.length>128)throw new Error(`Invalid keyword: ${JSON.stringify(e)}`);if([...e].some(r=>{let o=r.charCodeAt(0);return o<=n.ASCII_CONTROL_MAX||o===n.ASCII_DELETE}))throw new Error(`Invalid keyword: ${JSON.stringify(e)}`)}static quotePosixShellArg(e){let r=`'${e.replace(/'/g,"'\\''")}'`;return 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(we.isAbsolute(t))throw new Error(`Absolute paths are not allowed: ${t}`);let r=we.resolve(we.normalize(e),t);return n.ensurePathWithinRoot(e,r)}static ensurePathWithinRoot(e,t){let r=we.normalize(e),o=we.relative(r,t);if(o.split(we.sep)[0]===".."||we.isAbsolute(o))throw new Error(`Path escapes project root: ${t}`);return t}static isPathEscaping(e){let t=e.replace(/\\/g,"/");return t===".."||t.startsWith("../")||we.isAbsolute(e)}static isPathContained(e,t){let r=we.resolve(t,e),o=we.relative(t,r);return n.isPathEscaping(o)?{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 o;try{o=hc.realpathSync(t)}catch{return{contained:!1,reason:`Project root directory does not exist or cannot be resolved: ${t}`}}let i=we.resolve(o,e),s;try{s=hc.realpathSync(i)}catch{return{contained:!1,reason:`Path does not exist or cannot be resolved: ${i}`}}return n.isPathContained(s,o)}};var G=class n{rootDir;profile;constructor(e,t){this.rootDir=e,this.profile=t}static discover(e){let t=e;for(;;){let r=n.tryLoadProjectProfile(t);if(r)return new n(t,r);let o=H.dirname(t);if(o===t)break;t=o}throw new Error("Not in a valid project directory (project-level build-profile.json5 not found).")}static tryLoadProjectProfile(e){let t=H.join(e,"build-profile.json5");if(!Z.existsSync(t))return null;try{let r=Z.readFileSync(t,"utf-8"),o=Ct.parse(r);return o.app?o: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(i=>i.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!Z.existsSync(o))return"entry";try{let i=Z.readFileSync(o,"utf-8");return Ct.parse(i)?.module?.type||"entry"}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),"entry"}}findOwningModule(e){let t=H.normalize(e);for(let r of this.profile.modules){let o=H.normalize(H.join(this.rootDir,r.srcPath)),i=o+H.sep;if(t.startsWith(i)||t===o)return r.name}return null}getModuleProfile(e){let t=this.profile.modules.find(a=>a.name===e);if(!t)throw new Error(`Module '${e}' not found in project-level build-profile.json5.`);let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"build-profile.json5");if(!Z.existsSync(o))throw new Error(`Build profile for module '${e}' not found at ${o}.`);let i=Z.readFileSync(o,"utf-8");return Ct.parse(i)}getBundleName(){let e=H.join(this.rootDir,"AppScope","app.json5");if(Z.existsSync(e))try{let t=Z.readFileSync(e,"utf-8"),r=Ct.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=H.join(this.rootDir,"AppScope","app.json5");if(!Z.existsSync(e))return!1;try{let t=Z.readFileSync(e,"utf-8");return Ct.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 o=R.resolvePathWithinRoot(this.rootDir,r.srcPath),i=H.join(o,"src","main","module.json5");if(!Z.existsSync(i))return"EntryAbility";try{let s=Z.readFileSync(i,"utf-8"),c=Ct.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 ${i}:`,s),"EntryAbility"}}validateProduct(e){if(!/^[\da-zA-Z_-]+$/.test(e))throw new Error(`Invalid product name '${e}'. Product names must only contain letters, digits, underscores, and hyphens.`);if(!this.profile.app.products?.some(r=>r.name===e)){let r=this.profile.app.products?.map(o=>o.name).join(", ")||"none";throw new Error(`Product '${e}' not found in project configuration. Available products: ${r}`)}}getModuleDependencies(e){let t=this.profile.modules.find(s=>s.name===e);if(!t)return[];let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"oh-package.json5");if(!Z.existsSync(o))return[];let i=[];try{let s=Z.readFileSync(o,"utf-8"),c=Ct.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=H.join(t.srcPath,d),S=R.resolvePathWithinRoot(this.rootDir,w),A=this.profile.modules.find(se=>H.resolve(this.rootDir,se.srcPath)===S);A&&i.push(A.name)}}catch{}return i}getModuleName(e){let t=this.profile.modules.find(i=>i.name===e);if(!t)return e;let r=R.resolvePathWithinRoot(this.rootDir,t.srcPath),o=H.join(r,"src","main","module.json5");if(!Z.existsSync(o))return e;try{let i=Z.readFileSync(o,"utf-8");return Ct.parse(i)?.module?.name||e}catch(i){return console.warn(`Warning: Failed to parse ${o}:`,i),e}}collectNonHarDependentModuleList(e){let t=[],r=[],o=new Set;for(r.push(e),o.add(e);r.length>0;){let i=r.shift();this.getModuleType(i)!=="har"&&t.push(i);let a=this.getModuleDependencies(i);for(let c of a)o.has(c)||(r.push(c),o.add(c))}return t}resolveModuleMetadata(e,t,r){this.validateProduct(r);let o=this.profile.modules.find(l=>l.name===e);if(!o){let l=this.getRunnableModuleNames();throw new Error(`Module '${e}' not found. Available modules: ${l}`)}let i=this.getModuleType(e)==="shared",s=i?"hspName":"hapName",a=this.buildOutputPath(o.srcPath,r,["intermediates",i?"hsp_metadata":"hap_metadata",t,"output_metadata.json"]);if(!Z.existsSync(a))throw new Error(`Build metadata not found for module '${e}' at ${a}. Build the project first.`);let c=this.parseOutputMetadata(a,s);return{moduleNode:o,isShared:i,metadataPath:a,metadata:c}}findArtifactPath(e,t,r,o="default"){let{moduleNode:i,isShared:s,metadata:a}=this.resolveModuleMetadata(e,t,o),{packageName:c,isSigned:l}=a,d=c;if(!l){let S=this.getSignedHapName(c,i.srcPath,o,t);S&&(d=S)}let h=s?"-signed.hsp":"-signed.hap";if(!r&&!d.endsWith(h))throw new Error(`Target device is a real device, but the artifact for '${e}' is not signed. Real devices cannot install unsigned packages.`);let w=this.buildOutputPath(i.srcPath,o,["outputs",t,d]);if(!Z.existsSync(w))throw new Error(`Generated package file not found in ${w}.`);return w}findRemoteHspPaths(e,t,r="default"){let{moduleNode:o,metadata:i}=this.resolveModuleMetadata(e,t,r),s=[],a=new Set;for(let{hspPath:c}of i.dependRemoteHsps){if(a.has(c))continue;a.add(c);let l=H.isAbsolute(c)?c:this.buildOutputPath(o.srcPath,r,["outputs",t,c]);if(!Z.existsSync(l))throw new Error(`Remote HSP dependency not found: ${l}`);s.push(l)}return s}getSignedHapName(e,t,r,o){let i=null;if(e.endsWith("-unsigned.hap")?i=e.replace("-unsigned.hap","-signed.hap"):e.endsWith("-unsigned.hsp")&&(i=e.replace("-unsigned.hsp","-signed.hsp")),!i)return null;let s=this.buildOutputPath(t,r,["outputs",o,i]);return Z.existsSync(s)?i:null}buildOutputPath(e,t,r){let o=R.resolvePathWithinRoot(this.rootDir,e),i=H.resolve(o,"build",t,...r);return R.ensurePathWithinRoot(this.rootDir,i)}collectRemoteHsps(e){return e.flatMap(t=>{let r=t.dependRemoteHsps;return Array.isArray(r)?r.filter(o=>!!(o.hspName&&o.hspPath)).map(o=>({hspName:o.hspName,hspPath:o.hspPath})):[]})}parseOutputMetadata(e,t){let r=Z.readFileSync(e,"utf-8"),o=Ct.parse(r),i,s=!1,a=Array.isArray(o)?o:[o];for(let l of a)i||(i=l[t]),s||(s=l.isSigned===!0);if(!i)throw new Error(`Could not find ${t} in output_metadata.json at ${e}`);this.validatePackageName(i);let c=this.collectRemoteHsps(a);return{packageName:i,isSigned:s,dependRemoteHsps:c}}validatePackageName(e){let t=H.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 Ou}from"child_process";import V from"fs";import*as Se from"os";import*as v from"path";import Iu from"fs";import*as ki from"os";import*as Ti from"path";import lv from"regedit";import{execFileSync as av}from"child_process";import bu from"fs";import*as Eu from"os";import*as gc from"path";function Ri(n,e){let t=gc.join(n,"Contents","Info.plist");if(!bu.existsSync(t)){m(`[ToolProvider] Info.plist not found at: ${t}`);return}for(let[r,o]of[["/usr/libexec/PlistBuddy",["-c",`Print :${e}`,t]],["plutil",["-extract",e,"raw","-o","-",t]]])try{let i=av(r,o,{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(i&&!i.includes("Does Not Exist"))return i}catch{}}function cv(n){let e=Ri(n,"CFBundleShortVersionString");if(!e)return Ri(n,"CFBundleVersion");let t=e.split(".").slice(0,3).join(""),r=[Ri(n,"CFBundleVersion"),Ri(n,"CFBundleGetInfoString")?.match(/DS-[\d.]+/)?.[0]];for(let o of r){let i=o?.split(".").at(-1)?.replace(new RegExp(`^${t}`),"");if(i&&/^\d+$/.test(i))return`${e}.${i}`}return e}function so(n){if(Eu.platform()==="darwin")return cv(n);let e=gc.join(n,"product-info.json");try{let t=JSON.parse(bu.readFileSync(e,"utf8")).version;return typeof t=="string"&&t.trim()?t.trim():void 0}catch{return}}function ao(n,e){let t=Math.max(n.split(".").length,e.split(".").length);for(let r=0;r<t;r++){let o=Number(n.split(".")[r]??0)-Number(e.split(".")[r]??0);if(o)return o}return 0}function dv(n){return n.filter(e=>{try{return Iu.statSync(e).isDirectory()}catch{return!1}})}function uv(){let n=[];for(let e of[Ti.join(ki.homedir(),"Applications"),"/Applications"])try{n.push(...Iu.readdirSync(e).filter(t=>t.endsWith(".app")&&t.toLowerCase().includes("deveco")).map(t=>Ti.join(e,t)))}catch{}return n}function Pu(n){return new Promise((e,t)=>lv.list(n,(r,o)=>r?t(r):e(o)))}async function Cu(n,e,t){let o=((await Pu([n]))[n]?.keys??[]).filter(e).map(s=>`${n}\\${s}`);if(o.length===0)return[];let i=await Pu(o);return o.flatMap(s=>{let a=i[s]?.values?.[t]?.value;return a?[a]:[]})}async function pv(){let n=[Ti.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 Cu(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 Cu(e,()=>!0,""))}catch{}return n}async function Au(){let n=ki.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"?uv():await pv(),t=dv(e).flatMap(r=>{let o=so(r);return o?(m(`[ToolProvider] ${r} => version ${o}`),[{root:r,version:o}]):(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,o)=>ao(o.version,r.version)>0?o:r)}import*as Du from"fs";import*as ke from"path";function co(n,e){let t=ke.relative(e,n);return t===""||!ke.isAbsolute(t)&&!t.startsWith(`..${ke.sep}`)&&t!==".."}function yt(n){let e=ke.resolve(n),t=[],r=e;for(;;)try{let o=Du.realpathSync(r);return t.length===0?o:ke.join(o,...t.reverse())}catch(o){if(o.code!=="ENOENT")throw o;let i=ke.dirname(r);if(i===r)return e;t.push(ke.basename(r)),r=i}}function xi(n,e){let t=yt(e),r=yt(n);return co(r,t)?r:null}function Ni(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Li(n){let e=Ni(n);if(!e)throw new Error("Path must not be empty.");return yt(e)}var lo={LOGIN_TIMEOUT_MS:6e5,HTTP_TIMEOUT_MS:2e4,TOKEN_VALIDITY_DAYS:30},Oi={USER_AGENT:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",ACCEPT_LANGUAGE:"zh-CN"};var ve={APP_ID:"1009",CONFIG_DIR_NAME:".config",APP_NAME:"deveco-cli",TOKEN_FILE_NAME:"token.enc",KEY_FILE_NAME:"token.dek",API_VERSION:"1.0.0",AUTH_SOURCE_DEVECO_CODE:"deveco-code"},q={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"},Nn={ALGORITHM:"aes-256-gcm",KEY_LENGTH:32,IV_LENGTH:12,KEK_VERSIONS:["kek-v1","kek-v2","kek-v3"]},uo={baseUrl:q.LOGIN_URL,authUrl:q.AUTH_APPLY_PATH,tempTokenCheckUrl:q.TEMP_TOKEN_CHECK_PATH,jwtTokenCheckUrl:q.JWT_TOKEN_CHECK_PATH,successRedirectUrl:q.LOGIN_SUCCESS_PATH,failedRedirectUrl:q.LOGIN_FAILED_PATH,logoutUrl:q.LOGOUT_PATH,agcTeamListUrl:q.AGC_TEAM_LIST_URL,appId:ve.APP_ID,timeout:lo.LOGIN_TIMEOUT_MS,countryCode:"CN"};import{homedir as Xt}from"os";import It from"path";import{xdgConfig as fv}from"xdg-basedir";var ue={"trae-cn":It.join(Xt(),".trae-cn"),opencode:It.join(fv,"opencode"),cursor:It.join(Xt(),".cursor"),codebuddy:It.join(Xt(),".codebuddy"),qoder:It.join(Xt(),".qoder"),"claude-code":It.join(Xt(),".claude"),codex:It.join(Xt(),".codex"),bitfun:It.join(Xt(),".bitfun"),opendesk:It.join(Xt(),".opendesk")};import Zt from"path";import*as Ru from"os";function b(){return yc().toLowerCase().includes("openharmony")}function yc(){return Ru.platform()}var wc="https://matrix.openharmony.cn",ot={TAGS_API_URL:`${wc}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${wc}/api/registry/skill/skills`,SKILL_API_BASE:`${wc}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},Tu={"trae-cn":{path:Zt.join(ue["trae-cn"],"skills"),displayName:"trae-cn"},opencode:{path:Zt.join(ue.opencode,"skills"),displayName:"opencode"},cursor:{path:Zt.join(ue.cursor,"skills"),displayName:"cursor"},codebuddy:{path:Zt.join(ue.codebuddy,"skills"),displayName:"codebuddy"},qoder:{path:Zt.join(ue.qoder,"skills"),displayName:"qoder"},"claude-code":{path:Zt.join(ue["claude-code"],"skills"),projectPath:".claude/skills",displayName:"claude-code"},codex:{path:Zt.join(ue.codex,"skills"),displayName:"codex"}},ku={opencode:{path:Zt.join(ue.opencode,"skills"),displayName:"opencode"}};function At(){return b()?ku:Tu}import{homedir as po}from"os";import Be from"path";var wt="deveco-mcp";var Qt={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:Be.join(ue.opencode,"opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(po(),"AppData","Roaming"),"Trae CN","User"):Be.join(po(),"Library","Application Support","Trae CN","User"),"mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:Be.join(ue.cursor,"mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:Be.join(ue.codebuddy,"mcp.json"),projectConfigPath:".codebuddy/mcp.json",mcpServersKey:"mcpServers",format:"standard"},qoder:{name:"qoder",displayName:"Qoder",supportsGlobal:!0,globalConfigPath:Be.join(process.platform==="win32"?Be.join(process.env.APPDATA??Be.join(po(),"AppData","Roaming"),"Qoder","SharedClientCache"):Be.join(po(),"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:Be.join(po(),".claude.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"claude-code"},codex:{name:"codex",displayName:"Codex",supportsGlobal:!0,globalConfigPath:Be.join(ue.codex,"config.toml"),projectConfigPath:".codex/config.toml",mcpServersKey:"mcp_servers",format:"codex"}};function Nu(n){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:n??"."},enabled:!0}}function xu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"."},enabled:!0}}function Lu(n){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:n??"${workspaceFolder}"}}}function Mi(n,e){return n.format==="opencode"?Nu(e):n.format==="claude-code"||n.format==="codex"?xu(e):Lu(e)}var it={OH_PACKAGE_JSON5:"oh-package.json5",BUILD_PROFILE_JSON5:"build-profile.json5",SYNC_OUTPUT_PATH:".hvigor/outputs/sync/output.json"};var vc="https://developer.huawei.com/consumer/cn/download/";var mv=/^#\s*Version:\s*(\S+)/,hv="26.0.0.810",gv=["sdk","default","openharmony","native","llvm","bin","clangd"];function yv(n){try{let e=JSON.parse(V.readFileSync(n,"utf8")),t=Number(e.apiVersion??e.data?.apiVersion);return Number.isInteger(t)&&t>=17?t:void 0}catch{return}}function wv(n){let e=v.join(n,"default","openharmony");return[v.join(n,"default","sdk-pkg.json"),...["toolchains","native","previewer"].map(t=>v.join(e,t,"oh-uni-package.json"))]}var I=class n{constructor(e,t,r,o,i,s,a,c,l,d,h="",w=""){this._sourceType=e;this._toolchainRoot=t;this._devecoStudioPath=r;this._nodePath=o;this._ohpmJsPath=i;this._hvigorJsPath=s;this._javaPath=a;this._sdkPath=c;this._hdcPath=l;this._emulatorPath=d;this._clangdPath=h;this._lspServerPath=w}_sourceType;_toolchainRoot;_devecoStudioPath;_nodePath;_ohpmJsPath;_hvigorJsPath;_javaPath;_sdkPath;_hdcPath;_emulatorPath;_clangdPath;_lspServerPath;static verifiedPaths=new Set;static powerShellPath;static powerShellModulesPath;static installSourcePromise;get sourceType(){return this._sourceType}get toolchainRoot(){return this._toolchainRoot}get devecoStudioPath(){return this._devecoStudioPath}get nodePath(){return this.verify(this._nodePath)}get ohpmJsPath(){return this._ohpmJsPath}get hvigorJsPath(){return this._hvigorJsPath}get codelinterPath(){return n.resolveCodelinterPath(this._toolchainRoot,this._sourceType)}get javaPath(){return this._javaPath?this.verify(this._javaPath):""}get sdkPath(){return this._sdkPath}get hdcPath(){return this.verify(this._hdcPath)}get emulatorPath(){return this.verify(this._emulatorPath)}get emulatorLauncherPath(){return this.emulatorPath}get clangdPath(){return this.verify(this._clangdPath)}get lspServerPath(){return this.verify(this._lspServerPath)}verify(e){return e&&(n.verifiedPaths.has(e)||(n.verifySignature(e),n.verifiedPaths.add(e)),e)}assertJava(){if(!b()){if(this._sourceType==="clt"&&!this._javaPath&&(this._javaPath=n.resolveCltJava(!0)),!this._javaPath)throw new Error("Java runtime is required to run hvigor. Set JAVA_HOME or add Java to PATH.");this.verify(this._javaPath)}}assertEmulator(){this.verify(this._emulatorPath)}assertStudio(){if(this._sourceType==="clt")throw new Error("This operation requires DevEco Studio. Set DEVECO_CLI_STUDIO_PATH to a DevEco Studio installation.")}assertLsp(){this.assertStudio()}static compareVersion(e,t){return ao(e,t)}static async checkVersion(){if(b())return;let e=await n.resolveInstallSource();(e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)).assertVersion()}static async new(){if(b())return n.fromOpenHarmony();let e=await n.resolveInstallSource();return e.sourceType==="clt"?n.fromCLT(e.toolchainRoot):n.fromIDE(e.toolchainRoot,e.sourceType)}static fromCLT(e){let t=n.buildToolPaths(e,"clt");return n.assertBuiltPathsInsideRoot(e,t,!1),new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,n.resolveCltJava(!1),t.sdkPath,t.hdcPath,t.emulatorPath)}static fromIDE(e,t="studio"){let r=n.buildToolPaths(e,"studio");return n.assertBuiltPathsInsideRoot(e,r,!0),new n(t,e,e,r.nodePath,r.ohpmJsPath,r.hvigorJsPath,r.javaPath,r.sdkPath,r.hdcPath,r.emulatorPath,n.resolveClangdPath(e),n.resolveLspServerPath(e))}static fromOpenHarmony(){let e=process.env.COMMAND_LINE_TOOL_PATH;if(!e)throw new Error("COMMAND_LINE_TOOL_PATH environment variable is not set.");let t=n.buildOpenHarmonyToolPaths(e);n.assertBuiltPathsInsideRoot(e,t,!1);let r=v.join(e,"clangd","clangd"),o=v.join(e,"ace-server","out","index.js");return new n("clt",e,void 0,t.nodePath,t.ohpmJsPath,t.hvigorJsPath,"",t.sdkPath,t.hdcPath,t.emulatorPath,r,o)}static buildOpenHarmonyToolPaths(e){let t=v.join(e,"sdk");return{nodePath:v.join(e,"node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains","hdc"),emulatorPath:""}}static devecoContentRootForClangd(e){return Se.platform()==="darwin"&&e.endsWith(".app")?v.join(e,"Contents"):e}static clangdCandidatesFromDevecoHome(e){let t=new Set,r=[e,n.devecoContentRootForClangd(e)];for(let o of r){let i=v.join(o,...gv);t.add(Se.platform()==="win32"?i+".exe":i)}return[...t]}static resolveClangdPath(e){let t=n.clangdCandidatesFromDevecoHome(e);for(let r of t)if(V.existsSync(r))return r;return""}static resolveLspServerPath(e){let t=Se.platform(),r;if(t==="win32")r=v.join(e,"plugins","openharmony");else if(t==="darwin")r=v.join(e,"Contents","plugins","openharmony");else return"";let o=v.join(r,"ace-server","out","index.js");return V.existsSync(o)?o:""}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"){b()||(this.assertStudio(),n.assertMinimumVersion(so(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,o,i){if(!e)throw new Error(`Failed to determine ${t} version from ${r} at ${i}`);if(!/^\d+(?:\.\d+){1,3}$/.test(e))throw new Error(`Invalid ${t} version "${e}" from ${r} at ${i}`);if(ao(e,o)<0)throw new Error(`The detected ${t} version is ${e}, which is below the minimum required version ${o}. Upgrade before using deveco-cli:
|
|
5
5
|
${vc}`)}static resolveCodelinterPath(e,t){let r=n.getCodelinterCandidates(e,t),o=r.find(n.isFile);if(!o){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 i=yt(e),s=yt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=Se.platform()==="darwin"?["Contents"]:[];return[v.join(e,...r,"plugins","codelinter","run","index.js"),v.join(e,...r,"plugins","codelinter","index.js"),v.join(e,...r,"tools","codelinter","bin","codelinter.js"),v.join(e,...r,"tools","codelinter","codelinter.js")]}return[v.join(e,"codelinter","index.js"),v.join(e,"codelinter","run","index.js"),v.join(e,"tool","codelinter","bin","codelinter.js"),v.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return V.existsSync(v.join(e,"version.txt"));let r=Se.platform()==="darwin"?v.join(e,"Contents"):e,o=Se.platform()==="darwin"?v.join(r,"Info.plist"):v.join(r,"product-info.json");if(!V.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(V.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=v.join(e,"sdk"),r=Se.platform()==="win32",o=r?".exe":"";return{nodePath:r?v.join(e,"tool","node","node.exe"):v.join(e,"tool","node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains",`hdc${o}`),emulatorPath:v.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=Se.platform()==="darwin",r=Se.platform()==="win32",o=t?v.join(e,"Contents"):e,i=v.join(o,"tools"),s=v.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?v.join(i,"node","node.exe"):v.join(i,"node","bin","node"),ohpmJsPath:v.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?v.join(e,"jbr","bin","java.exe"):t?v.join(o,"jbr","Contents","Home","bin","java"):v.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:v.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:v.join(i,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return V.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return V.existsSync(e)&&V.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,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Au();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=Li(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&Se.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=yt(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)a&&n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(xi(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,o){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}: ${o}`)}static normalizeMacStudioRoot(e){let t=`${v.sep}Contents`,r=v.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return V.readFileSync(v.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(mv)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(v.join(t,"bin"))??n.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(v.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return V.realpathSync(i);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(Se.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>v.join(e,r)).find(V.existsSync)}getMaxApiLevel(){for(let e of wv(this.sdkPath)){let t=yv(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Se.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=v.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=v.join(r,"resources","apiChange"),i=v.join(r,"api-change-scan.js");if(!V.existsSync(o)||!V.existsSync(i)){let s=so(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${hv}. Upgrade before using 'check compat' at ${vc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}static verifySignature(e){if(!V.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Se.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&v.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!V.statSync(e).isFile())throw new Error;V.accessSync(e,V.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=v.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=V.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=v.join(v.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=V.mkdtempSync(v.join(Se.tmpdir(),"deveco-verify-")),o=v.join(r,"Verify-Signature.ps1");V.writeFileSync(o,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let i=Ou(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(i);return{signed:Number(s.Status)===0}}catch(i){return m(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!1}}finally{V.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return Ou("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as vv}from"execa";import*as Dt from"path";import*as _i from"fs";import*as Sc from"os";var xe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let i=Dt.dirname(e.javaPath);o.PATH=`${i}${Dt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=Dt.dirname(i))}b()&&(o.HVIGOR_USER_HOME=Dt.join(Sc.homedir(),".hvigor")),this.env=o}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){b()||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(!_i.existsSync(t))return null;try{let r=_i.readFileSync(t,"utf-8"),o=JSON.parse(r),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(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||Dt.join(Sc.homedir(),".hvigor");return Dt.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await vv(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as Sv}from"execa";var en=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`),await Sv(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as bv}from"fs/promises";import{dirname as Ev,resolve as Pv}from"path";import{execa as Cv}from"execa";import{lock as bc,check as uM}from"proper-lockfile";function Ec(n){return Pv(n,".hvigor",".build-lock")}function Iv(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Mu(n){let e=Ev(Ec(n));if(await bv(e,{recursive:!0}),process.platform==="win32")try{await Cv("attrib",["+h",e])}catch{}}async function Av(n,e){let t=new AbortController,r=Iv(e);await Mu(n);let o={lockfilePath:Ec(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await bc(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await bc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Rt(n,e,t){let{release:r,signal:o}=await Av(n,t);try{return await e(o)}finally{await r()}}async function Fi(n,e){let t=new AbortController;await Mu(n);let r={lockfilePath:Ec(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await bc(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as tn from"fs";import*as Ln from"path";import Dv from"json5";var Rv=1e3;function Hi(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Ln.join(n,it.SYNC_OUTPUT_PATH);if(!tn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=tn.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Tv(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Ln.join(n,it.OH_PACKAGE_JSON5),i=ji(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Ln.join(n,it.BUILD_PROFILE_JSON5),a=ji(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Ln.join(n,l.srcPath,it.OH_PACKAGE_JSON5),h=ji(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Ln.join(n,l.srcPath,it.BUILD_PROFILE_JSON5),S=ji(w,t,l.name);if(S.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${S.reason}`),S}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function ji(n,e,t){if(!tn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=tn.statSync(n).mtimeMs;return r-e>Rv?{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 Tv(n){let e=Ln.join(n,it.BUILD_PROFILE_JSON5);try{let t=tn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Dv.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Ge from"fs";import*as at from"path";import*as Gu from"util";import*as M from"fs";import*as qi from"path";import te from"fs";import*as $i from"os";import*as z from"path";import kv from"json5";var _u=3;function Ui(n){if(!te.existsSync(n)||!te.statSync(n).isDirectory())return!1;let e=te.existsSync(z.join(n,"build-profile.json5")),t=te.existsSync(z.join(n,"hvigorfile.js"))||te.existsSync(z.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=te.readFileSync(z.join(n,"build-profile.json5"),"utf-8");return kv.parse(r).app!==void 0}catch{return!1}}function Pc(n,e,t){if(e>=t)return null;let r=xv(n),o=Nv(r);if(o)return o;for(let i of r){let s=Pc(i,e+1,t);if(s)return s}return null}function xv(n){try{let e=te.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(z.join(n,r.name));return t}catch{return[]}}function Nv(n){for(let e of n)if(Ui(e))return e;return null}function Tt(n){if(!n||n.trim()==="")return null;let e=z.resolve(n),t;try{t=te.realpathSync(e)}catch{t=e}if(!te.existsSync(t))return null;if(Ui(t))return t;let r=t;for(let o=1;o<=3;o++){let i=z.dirname(r);if(i===r)break;if(Ui(i))return i;r=i}if(te.statSync(t).isDirectory()){let o=Pc(t,0,_u);if(o)return o}return null}function Bi(n){if(!n||n.trim()==="")return null;let e=z.resolve(n),t;try{t=te.realpathSync(e)}catch{t=e}return!te.existsSync(t)||!te.statSync(t).isDirectory()?null:Ui(t)?t:Pc(t,0,_u)}var Cc=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function sr(n){return z.join(n,...Cc)}function Fu(n){return new Promise(e=>setTimeout(e,n))}var Lv=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function On(n){let e=z.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Lv.has(e)}function Wi(n){return z.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function pe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Ov(n){return pe(n)}function Mn(n){let e=Ov(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function nn(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??z.join($i.homedir(),"AppData","Local");return z.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?z.join($i.homedir(),"Library","Logs","devecocli-mcp-server"):z.join($i.homedir(),".local","share","devecocli-mcp-server","logs")}function ju(n,e){let t=Mv(e),r=_v(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Fv(t,n,s);return jv(e,a),o}function Mv(n){let e;try{e=te.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function _v(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function Fv(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function jv(n,e){try{te.mkdirSync(z.dirname(n),{recursive:!0})}catch{}try{te.writeFileSync(n,e.join(`
|
|
8
|
+
`)}`)}let i=yt(e),s=yt(o);return n.assertInsideRoot(s,i,"codelinter"),s}static getCodelinterCandidates(e,t){if(t==="studio"){let r=Se.platform()==="darwin"?["Contents"]:[];return[v.join(e,...r,"plugins","codelinter","run","index.js"),v.join(e,...r,"plugins","codelinter","index.js"),v.join(e,...r,"tools","codelinter","bin","codelinter.js"),v.join(e,...r,"tools","codelinter","codelinter.js")]}return[v.join(e,"codelinter","index.js"),v.join(e,"codelinter","run","index.js"),v.join(e,"tool","codelinter","bin","codelinter.js"),v.join(e,"tool","codelinter","codelinter.js")]}static isValidRoot(e,t){if(!n.isDirectory(e))return!1;if(t==="clt")return V.existsSync(v.join(e,"version.txt"));let r=Se.platform()==="darwin"?v.join(e,"Contents"):e,o=Se.platform()==="darwin"?v.join(r,"Info.plist"):v.join(r,"product-info.json");if(!V.existsSync(o))return!1;let i=n.buildToolPaths(e,"studio");return[i.nodePath,i.ohpmJsPath,i.hvigorJsPath].every(V.existsSync)}static buildToolPaths(e,t){return t==="clt"?n.buildCltToolPaths(e):n.buildStudioToolPaths(e)}static buildCltToolPaths(e){let t=v.join(e,"sdk"),r=Se.platform()==="win32",o=r?".exe":"";return{nodePath:r?v.join(e,"tool","node","node.exe"):v.join(e,"tool","node","bin","node"),ohpmJsPath:v.join(e,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(e,"hvigor","bin","hvigorw.js"),javaPath:"",sdkPath:t,hdcPath:v.join(t,"default","openharmony","toolchains",`hdc${o}`),emulatorPath:v.join(e,"emulator",r?"Emulator.exe":"Emulator")}}static buildStudioToolPaths(e){let t=Se.platform()==="darwin",r=Se.platform()==="win32",o=t?v.join(e,"Contents"):e,i=v.join(o,"tools"),s=v.join(o,"sdk"),a=r?".exe":"";return{nodePath:r?v.join(i,"node","node.exe"):v.join(i,"node","bin","node"),ohpmJsPath:v.join(i,"ohpm","bin","pm-cli.js"),hvigorJsPath:v.join(i,"hvigor","bin","hvigorw.js"),javaPath:r?v.join(e,"jbr","bin","java.exe"):t?v.join(o,"jbr","Contents","Home","bin","java"):v.join(o,"jbr","bin","java"),sdkPath:s,hdcPath:v.join(s,"default","openharmony","toolchains",`hdc${a}`),emulatorPath:v.join(i,"emulator",r?"Emulator.exe":"Emulator")}}static isFile(e){try{return V.statSync(e).isFile()}catch{return!1}}static isDirectory(e){try{return V.existsSync(e)&&V.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,o,i]of e){let s=process.env[r]?.trim();if(s){let a=n.resolveExplicitRoot(s,o,r);return m(`[ToolProvider] Using ${r} \u2192 ${a}`),{sourceType:i,toolchainRoot:a}}}let t=await Au();return m(`[ToolProvider] Using auto \u2192 ${t.root} (${t.version})`),{sourceType:"studio",toolchainRoot:t.root}}static resolveExplicitRoot(e,t,r){let o;try{o=Li(e)}catch(i){throw new Error(`Invalid ${r}: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return t==="studio"&&Se.platform()==="darwin"&&(o=n.normalizeMacStudioRoot(o)),n.isValidRoot(o,t)?o:n.throwInvalidSource(o,t,r,e)}static assertBuiltPathsInsideRoot(e,t,r){let o=yt(e),i=[["node",t.nodePath],["ohpm",t.ohpmJsPath],["hvigor",t.hvigorJsPath],["sdk",t.sdkPath],["hdc",t.hdcPath],["emulator",t.emulatorPath]];r&&t.javaPath&&i.push(["java",t.javaPath]);for(let[s,a]of i)a&&n.assertInsideRoot(a,o,s)}static assertInsideRoot(e,t,r){if(xi(e,t)===null)throw new Error(`Unsafe toolchain path: ${r} resolves outside the toolchain root`)}static throwInvalidSource(e,t,r,o){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}: ${o}`)}static normalizeMacStudioRoot(e){let t=`${v.sep}Contents`,r=v.normalize(e);return r.endsWith(t)?r.slice(0,-t.length):r}static readCltVersion(e){try{return V.readFileSync(v.join(e,"version.txt"),"utf-8").split(/\r?\n/).map(t=>t.match(mv)?.[1]?.trim()).find(Boolean)}catch{return}}static resolveCltJava(e){let t=process.env.JAVA_HOME?.trim(),r=t&&(n.javaIn(v.join(t,"bin"))??n.javaIn(t)),o=(process.env.Path??process.env.PATH??"").split(v.delimiter).map(s=>n.javaIn(s.trim())).find(Boolean),i=r??o;if(i)return V.realpathSync(i);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(Se.platform()==="win32"?["java.exe","java.cmd"]:["java"]).map(r=>v.join(e,r)).find(V.existsSync)}getMaxApiLevel(){for(let e of wv(this.sdkPath)){let t=yv(e);if(t!==void 0)return t}return 23}detectApiLevel(){return this.getMaxApiLevel()}_apiscanPaths;getApiscanPaths(){if(this._apiscanPaths)return this._apiscanPaths;let e=Se.platform();if(e!=="darwin"&&e!=="win32")throw new Error(`Unsupported platform: ${e}. compat only supports macOS and Windows.`);if(!this._devecoStudioPath)throw new Error("DevEco Studio is required for compatibility checking. Set DEVECO_CLI_STUDIO_PATH or install DevEco Studio.");let t=e==="darwin"?"Contents":"",r=v.join(this._devecoStudioPath,t,"plugins","harmony","arkanalyzer-apiscan"),o=v.join(r,"resources","apiChange"),i=v.join(r,"api-change-scan.js");if(!V.existsSync(o)||!V.existsSync(i)){let s=so(this._toolchainRoot)??"unknown";throw new Error(`A required component is missing. The detected DevEco Studio version is ${s}. The minimum required version is ${hv}. Upgrade before using 'check compat' at ${vc}`)}return this._apiscanPaths={apiChangeDir:o,scriptPath:i},this._apiscanPaths}static verifySignature(e){if(!V.existsSync(e))throw new Error(`executable not found at: ${e}`);let t=Se.platform();if(t==="linux"){n.assertExecutable(e);return}if(t==="win32"&&v.extname(e).toLowerCase()===".exe"){n.assertSigned(n.verifyWindowsSignature(e),e);return}t==="darwin"&&(n.assertExecutable(e),n.assertSigned(n.verifyMacSignature(e),e))}static assertExecutable(e){try{if(!V.statSync(e).isFile())throw new Error;V.accessSync(e,V.constants.X_OK)}catch{throw new Error(`executable is not accessible: ${e}`)}}static assertSigned(e,t){if(!e.signed)throw new Error(`The executable is not digitally signed: ${t}`)}static findPowerShellPath(){if(n.powerShellPath!==void 0)return n.powerShellPath;let e=v.join(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe");return n.powerShellPath=V.existsSync(e)?e:"",n.powerShellPath&&(n.powerShellModulesPath=v.join(v.dirname(n.powerShellPath),"Modules")),n.powerShellPath}static verifyWindowsSignature(e){let t=n.findPowerShellPath();if(!t)throw new Error("The PowerShell application was not found");let r=V.mkdtempSync(v.join(Se.tmpdir(),"deveco-verify-")),o=v.join(r,"Verify-Signature.ps1");V.writeFileSync(o,"Get-AuthenticodeSignature -FilePath $args[0] | ConvertTo-Json -Depth 3 -Compress","utf8");try{let i=Ou(t,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",o,e],{encoding:"utf8",timeout:5e3,stdio:["ignore","pipe","ignore"],env:{...process.env,PSModulePath:n.powerShellModulesPath}}),s=JSON.parse(i);return{signed:Number(s.Status)===0}}catch(i){return m(`[ToolProvider] verify Windows Signature, error msg: ${i}`),{signed:!1}}finally{V.rmSync(r,{recursive:!0,force:!0})}}static verifyMacSignature(e){try{return Ou("codesign",["-v",e],{encoding:"utf8",timeout:5e3,stdio:["ignore","ignore","ignore"]}),{signed:!0}}catch{return{signed:!1}}}};import{execa as vv}from"execa";import*as Dt from"path";import*as _i from"fs";import*as Sc from"os";var xe=class{toolProvider;projectRoot;env;silent;constructor(e,t,r=!1){this.toolProvider=e,this.projectRoot=t,this.silent=r;let o={...process.env,DEVECO_SDK_HOME:e.sdkPath};if(e.javaPath){let i=Dt.dirname(e.javaPath);o.PATH=`${i}${Dt.delimiter}${process.env.PATH||""}`,e.sourceType==="clt"&&(o.JAVA_HOME=Dt.dirname(i))}b()&&(o.HVIGOR_USER_HOME=Dt.join(Sc.homedir(),".hvigor")),this.env=o}async sync(e,t){let r=["--sync","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildProduct(e,t){let r=["assembleApp","-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(r)}async buildModules(e,t,r,o){let i=[...Array.from(o),"--mode","module","-p",`module=${r.join(",")}`,"-p",`product=${e}`,"-p",`buildMode=${t}`,"--analyze=normal","--parallel","--incremental"];await this.runHvigor(i)}async clean(){let e=["clean","--analyze=normal","--parallel","--no-daemon"];await this.runHvigor(e)}async stopDaemon(){b()||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(!_i.existsSync(t))return null;try{let r=_i.readFileSync(t,"utf-8"),o=JSON.parse(r),i=e??this.projectRoot,s=Object.values(o).filter(a=>a.cwdPath===i&&(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||Dt.join(Sc.homedir(),".hvigor");return Dt.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){b()&&(e=e.includes("--no-daemon")?e:["--no-daemon",...e]);let t=this.toolProvider.nodePath,r=[this.toolProvider.hvigorJsPath,...e];m(`Executing: ${t} ${r.join(" ")}`);let o=this.silent&&!process.env.DEVECO_CLI_DEBUG?"pipe":"inherit";await vv(t,r,{cwd:this.projectRoot,env:this.env,stdout:o,stderr:o})}};import{execa as Sv}from"execa";var en=class{toolProvider;projectRoot;constructor(e,t){this.toolProvider=e,this.projectRoot=t}async installAll(){let e=this.toolProvider.nodePath,t=["--no-deprecation",this.toolProvider.ohpmJsPath,"install","--all"];m(`Executing: ${e} ${t.join(" ")}`),await Sv(e,t,{cwd:this.projectRoot,env:{...process.env,DEVECO_SDK_HOME:this.toolProvider.sdkPath},stdout:"inherit",stderr:"inherit"})}};import{mkdir as bv}from"fs/promises";import{dirname as Ev,resolve as Pv}from"path";import{execa as Cv}from"execa";import{lock as bc,check as pM}from"proper-lockfile";function Ec(n){return Pv(n,".hvigor",".build-lock")}function Iv(n){let e=!1;return()=>{e||(e=!0,n?.())}}async function Mu(n){let e=Ev(Ec(n));if(await bv(e,{recursive:!0}),process.platform==="win32")try{await Cv("attrib",["+h",e])}catch{}}async function Av(n,e){let t=new AbortController,r=Iv(e);await Mu(n);let o={lockfilePath:Ec(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()};try{return{release:await bc(n,{...o,retries:0}),signal:t.signal}}catch(s){if(s&&typeof s=="object"&&"code"in s&&s.code!=="ELOCKED")throw s}return r(),{release:await bc(n,{...o,retries:{forever:!0,minTimeout:1e3,maxTimeout:1e3}}),signal:t.signal}}async function Rt(n,e,t){let{release:r,signal:o}=await Av(n,t);try{return await e(o)}finally{await r()}}async function Fi(n,e){let t=new AbortController;await Mu(n);let r={lockfilePath:Ec(n),realpath:!1,stale:5e3,update:2e3,onCompromised:()=>t.abort()},o;try{o=await bc(n,{...r,retries:0})}catch(i){if(i&&typeof i=="object"&&"code"in i&&i.code==="ELOCKED")return{acquired:!1};throw i}try{return{acquired:!0,result:await e(t.signal)}}finally{await o()}}import*as tn from"fs";import*as Ln from"path";import Dv from"json5";var Rv=1e3;function Hi(n){m(`[ProjectCheck] Checking sync required at project root: ${n}`);let e=Ln.join(n,it.SYNC_OUTPUT_PATH);if(!tn.existsSync(e)){let l={required:!0,reason:`sync baseline file not found: ${e}`};return m(`[ProjectCheck] ${l.reason}`),l}let t=tn.statSync(e).mtimeMs;m(`[ProjectCheck] Sync baseline: ${new Date(t).toISOString()} (${e})`);let r=Tv(n);if(r===null){let l={required:!0,reason:"failed to parse build-profile.json5"};return m(`[ProjectCheck] ${l.reason}`),l}let o=Ln.join(n,it.OH_PACKAGE_JSON5),i=ji(o,t,"root");if(i.required)return m(`[ProjectCheck] Root check: ${i.reason}`),i;let s=Ln.join(n,it.BUILD_PROFILE_JSON5),a=ji(s,t,"build-profile");if(a.required)return m(`[ProjectCheck] Build profile check: ${a.reason}`),a;for(let l of r){let d=Ln.join(n,l.srcPath,it.OH_PACKAGE_JSON5),h=ji(d,t,l.name);if(h.required)return m(`[ProjectCheck] Module '${l.name}' check: ${h.reason}`),h;let w=Ln.join(n,l.srcPath,it.BUILD_PROFILE_JSON5),S=ji(w,t,l.name);if(S.required)return m(`[ProjectCheck] Module '${l.name}' build-profile check: ${S.reason}`),S}let c=`all configuration files are up-to-date (sync baseline: ${new Date(t).toISOString()})`;return m(`[ProjectCheck] ${c}`),{required:!1,reason:c}}function ji(n,e,t){if(!tn.existsSync(n))return{required:!1,reason:`${t}: source not found, skip`};let r=tn.statSync(n).mtimeMs;return r-e>Rv?{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 Tv(n){let e=Ln.join(n,it.BUILD_PROFILE_JSON5);try{let t=tn.readFileSync(e,"utf-8");if(!t.trim())return null;let r=Dv.parse(t);if(typeof r!="object"||r===null)return null;let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):null}catch{return null}}import*as Ge from"fs";import*as at from"path";import*as Gu from"util";import*as M from"fs";import*as qi from"path";import te from"fs";import*as $i from"os";import*as z from"path";import kv from"json5";var _u=3;function Ui(n){if(!te.existsSync(n)||!te.statSync(n).isDirectory())return!1;let e=te.existsSync(z.join(n,"build-profile.json5")),t=te.existsSync(z.join(n,"hvigorfile.js"))||te.existsSync(z.join(n,"hvigorfile.ts"));if(!e||!t)return!1;try{let r=te.readFileSync(z.join(n,"build-profile.json5"),"utf-8");return kv.parse(r).app!==void 0}catch{return!1}}function Pc(n,e,t){if(e>=t)return null;let r=xv(n),o=Nv(r);if(o)return o;for(let i of r){let s=Pc(i,e+1,t);if(s)return s}return null}function xv(n){try{let e=te.readdirSync(n,{withFileTypes:!0}),t=[];for(let r of e)r.isDirectory()&&t.push(z.join(n,r.name));return t}catch{return[]}}function Nv(n){for(let e of n)if(Ui(e))return e;return null}function Tt(n){if(!n||n.trim()==="")return null;let e=z.resolve(n),t;try{t=te.realpathSync(e)}catch{t=e}if(!te.existsSync(t))return null;if(Ui(t))return t;let r=t;for(let o=1;o<=3;o++){let i=z.dirname(r);if(i===r)break;if(Ui(i))return i;r=i}if(te.statSync(t).isDirectory()){let o=Pc(t,0,_u);if(o)return o}return null}function Bi(n){if(!n||n.trim()==="")return null;let e=z.resolve(n),t;try{t=te.realpathSync(e)}catch{t=e}return!te.existsSync(t)||!te.statSync(t).isDirectory()?null:Ui(t)?t:Pc(t,0,_u)}var Cc=[b()?".bitfun":".idea",".deveco",b()?".cxx":"cxx","compile_commands.json"];function sr(n){return z.join(n,...Cc)}function Fu(n){return new Promise(e=>setTimeout(e,n))}var Lv=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function On(n){let e=z.extname(n).replace(/^\./,"").toLowerCase();return e.length>0&&Lv.has(e)}function Wi(n){return z.extname(n).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function pe(n){let e=n.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function Ov(n){return pe(n)}function Mn(n){let e=Ov(n);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function nn(){if(process.platform==="win32"){let n=process.env.LOCALAPPDATA??z.join($i.homedir(),"AppData","Local");return z.join(n,"devecocli-mcp-server","logs")}return process.platform==="darwin"?z.join($i.homedir(),"Library","Logs","devecocli-mcp-server"):z.join($i.homedir(),".local","share","devecocli-mcp-server","logs")}function ju(n,e){let t=Mv(e),r=_v(t,n);if(r!==null)return r;let o=Date.now(),s=`${n.replace(/:/g,"\\:")}=${o}`,a=Fv(t,n,s);return jv(e,a),o}function Mv(n){let e;try{e=te.readFileSync(n,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function _v(n,e){for(let t of n){let r=t.indexOf("=");if(r<=0||t.slice(0,r).replace(/\\:/g,":")!==e)continue;let i=parseInt(t.slice(r+1),10);return Number.isFinite(i)&&i>0?i:null}return null}function Fv(n,e,t){let r=!1,o=n.map(i=>{if(r)return i;let s=i.indexOf("=");return s<=0?i:i.slice(0,s).replace(/\\:/g,":")===e?(r=!0,t):i});return r||o.push(t),o}function jv(n,e){try{te.mkdirSync(z.dirname(n),{recursive:!0})}catch{}try{te.writeFileSync(n,e.join(`
|
|
9
9
|
`)+`
|
|
10
10
|
`,"utf8")}catch{}}function Ic(n,e,t="[Cleanup]"){try{let r=z.dirname(n);if(!te.existsSync(r))return;let o=Date.now();for(let i of te.readdirSync(r,{withFileTypes:!0}))i.isDirectory()&&Hv(z.join(r,i.name),o,e,t)}catch{}}function Hv(n,e,t,r){try{let{mtimeMs:o}=te.statSync(n);if(e-o<=t)return;te.rmSync(n,{recursive:!0,force:!0});let i=Math.floor((e-o)/1e3);console.error(`${r} Removed expired dir (age ${Math.floor(i/86400)}d ${Math.floor(i%86400/3600)}h): ${n}`)}catch(o){console.error(`${r} Failed to remove expired dir ${n}: ${o}`)}}var Hu="mcp-server.log",$v="mcp-server",Uv={maxSize:10*1024*1024,maxFiles:4},Ac=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={...Uv,...t},this.minLevel=e?"debug":"info",e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=nn(),this.currentLogFile=qi.join(this.logDir,Hu),M.existsSync(this.logDir)||M.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${o}`}getRotatedFileName(e,t){return qi.join(this.logDir,`${$v}-${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 o of e)if(o===Hu||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(o)){let i=qi.join(this.logDir,o),s=M.statSync(i);t.push({name:o,mtime:s.mtime,path:i})}t.sort((o,i)=>i.mtime.getTime()-o.mtime.getTime());let r=1+this.rotationOptions.maxFiles;for(let o=r;o<t.length;o++)try{M.unlinkSync(t[o].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&M.unlinkSync(t);for(let o=this.rotationOptions.maxFiles-1;o>=1;o--){let i=this.getRotatedFileName(e,o),s=this.getRotatedFileName(e,o+1);this.fileExists(i)&&M.renameSync(i,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 o=r.map(c=>c instanceof Error?`${c.name}: ${c.message}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),i=o?`${t} ${o}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${i}
|
|
11
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}},Ve=null;function _n(n=!1){Ve&&Ve.dispose(),Ve=new Ac(n)}function $u(){Ve&&(Ve.dispose(),Ve=null)}function Uu(){Ve&&Ve.flush()}function Bu(){return Ve?.getLogFilePath()??null}function Wu(){return Ve?.getLogDirectory()??null}function Gi(){return Ve||_n(!1),Ve}var g={debug:(n,...e)=>Gi().debug(n,...e),info:(n,...e)=>Gi().info(n,...e),warn:(n,...e)=>Gi().warn(n,...e),error:(n,...e)=>Gi().error(n,...e)};var Dc="";function zi(n){if(!n||n==="auto"||n==="stdout"||n==="none"){Dc="";return}Dc=n}function qu(){return Dc||(Wu()??"")}function Vi(n,...e){if(e.length===0)return n;try{return Gu.format(n,...e)}catch{return[n,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var f={info(n,...e){g.info(`[lsp] ${Vi(n,...e)}`)},warn(n,...e){g.warn(`[lsp] ${Vi(n,...e)}`)},error(n,...e){g.error(`[lsp] ${Vi(n,...e)}`)},debug(n,...e){g.debug(`[lsp] ${Vi(n,...e)}`)}};import*as fo from"fs";import*as mo from"os";import*as ar from"path";import Bv from"json5";var y={INITIALIZE:"initialize",INITIALIZED:"initialized",SHUTDOWN:"shutdown",EXIT:"exit",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DID_CLOSE:"textDocument/didClose",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",DEFINITION:"textDocument/definition",DECLARATION:"textDocument/declaration",REFERENCES:"textDocument/references",IMPLEMENTATION:"textDocument/implementation",COMPLETION:"textDocument/completion",COMPLETION_ITEM_RESOLVE:"completionItem/resolve",SIGNATURE_HELP:"textDocument/signatureHelp",CODE_ACTION:"textDocument/codeAction",PREPARE_RENAME:"textDocument/prepareRename",RENAME:"textDocument/rename",DOCUMENT_HIGHLIGHT:"textDocument/documentHighlight",DOCUMENT_LINK:"textDocument/documentLink",INLAY_HINT:"textDocument/inlayHint",DOCUMENT_SYMBOL:"textDocument/documentSymbol",WORKSPACE_SYMBOL:"workspace/symbol",DIAGNOSTIC:"textDocument/diagnostic",WORKSPACE_DIAGNOSTIC:"workspace/diagnostic",PREPARE_CALL_HIERARCHY:"textDocument/prepareCallHierarchy",INCOMING_CALLS:"callHierarchy/incomingCalls",OUTGOING_CALLS:"callHierarchy/outgoingCalls",PREPARE_TYPE_HIERARCHY:"textDocument/prepareTypeHierarchy",SUPERTYPES:"typeHierarchy/supertypes",SUBTYPES:"typeHierarchy/subtypes",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles",DID_CREATE_FILES:"workspace/didCreateFiles",DID_DELETE_FILES:"workspace/didDeleteFiles",PROGRESS:"$/progress",WINDOW_SHOW_MESSAGE:"window/showMessage",WINDOW_LOG_MESSAGE:"window/logMessage",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",ARKTS_ERROR:"arkts/error",CPP_INITIALIZED:"cpp/initialized",CPP_INITIALIZATION_FAILED:"cpp/initializationFailed",CPP_INDEXING_PROGRESS:"cpp/indexingProgress",CPP_SYNC_PROJECT:"cpp/syncProject",CPP_SYNC_COMPLETED:"cpp/syncCompleted",CPP_REINITIALIZING:"cpp/reinitializing",CPP_ERROR:"cpp/error",BROADCAST:"lsp/broadcast"},T="2.0";var Vu=8192,Rc=100,zu=.03,Ju=.7,ze=900*1e3,Ji="/data/app/sdk.org/sdk_1.0.0";function We(n){if(!fo.existsSync(n))return null;try{let e=fo.readFileSync(n,"utf-8");return e.trim()?Bv.parse(e):null}catch{return null}}function Yi(n,e){let t=Math.floor(mo.totalmem()/1048576),r=Math.floor(t*Ju),o,i;e!==void 0&&Number.isFinite(e)&&e>0?(o=e,i=`override(${e})`):(o=Vu,n>Rc&&(o+=(n-Rc)*zu*1024),i=`formula(moduleCount=${n})`);let s=r>0&&o>r;s&&(o=r);let a=Math.round(o);return f.info(`[computeLspServerMaxSize] source=${i}, physicalTotal=${t}MB, physicalCap(70%)=${r}MB, finalSize=${a}MB${s?" (capped)":""}`),a}function st(n){if(n.startsWith("file:"))return n;try{let e=ar.resolve(n),t=new URL(`file://${e}`).toString();if(mo.platform()==="win32"){let r=t.match(/^file:\/\/\/([A-Za-z]):/);if(r){let o=r[1].toUpperCase(),i=t.substring(`file:///${r[1]}:`.length);t=`file:///${o}%3A${i}`}}return t}catch{return n}}function cr(n){return n&&n.replace(/\\/g,"/")}function U(n){let e=ar.normalize(n).replace(/\\/g,"/");if(mo.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Yu(n){return ar.join(n,"build-profile.json5")}var kt=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Yu(this.projectRoot);try{let t=We(e);if(typeof t!="object"||t===null)return[];let r=t.modules;return Array.isArray(r)?r.filter(o=>{if(typeof o!="object"||o===null)return!1;let i=o;return typeof i.name=="string"&&typeof i.srcPath=="string"}):[]}catch(t){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};import*as Ku from"os";import*as Xu from"path";import{spawn as Wv}from"child_process";var Gv=600*1e3;function qv(n){let e=[],t=[];return n.stdout?.on("data",r=>{e.push(r.toString())}),n.stderr?.on("data",r=>{t.push(r.toString())}),{stdout:e,stderr:t}}function Ki(n){return n.join("")}function Vv(n,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
@@ -62,7 +62,7 @@ Available runnable modules:
|
|
|
62
62
|
Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Eo(`
|
|
63
63
|
Application '${t}': ${s}`))}else console.log(`
|
|
64
64
|
Application '${t}' installed successfully (no ability to launch).`)}var Jc=new ub("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/");b()||Jc.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.");Jc.action(async n=>{try{await gb(n)}catch(e){console.error(pb(e.message)),process.exit(1)}});async function fb(n,e,t,r,o){let i=new en(e,n.rootDir),s=new xe(e,n.rootDir),a=new Set,c=new Set;for(let{moduleName:w,targetName:S}of t)for(let A of n.collectNonHarDependentModuleList(w))a.add(`${A}@${S}`),c.add(A);let l=[...a],d=go(n,l),h={type:"modules",modulesToBuild:l,moduleTasks:d};for(let w of c)Qi.generate(n.rootDir,w,r,e);await Rt(n.rootDir,()=>yo(i,s,r,o,h,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
|
|
65
|
-
`+Eo("Build completed successfully."))}async function mb(n,e,t,r,o){let i=new xt(t),s=ne.from(t),a=r[0]?.moduleName||o[0];await Tp(n,e,t,i,s,a)}function hb(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}async function gb(n){let e=G.discover(process.cwd());console.warn(cs("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.hotreloadApply){await wb(n,e,t);return}if(n.hotreload){await yb(n,e,t);return}if(n.apply){await Sb(n,e,t);return}await Np(n,e,t)}async function yb(n,e,t){if(n.hotreload==="stop"){await Ap(t,e);return}let o=zc(e,n.module).map(Vc),{moduleName:i,targetName:s}=o[0];Uc(n.module,i);let a=new xt(t),c=ne.from(t),l=await ds(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),S=kp(e,o,n.ability);es.generate(e.rootDir,i,h,t);let A=new xe(t,e.rootDir);console.log(Eo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await A.ensureDaemonRunning();let se=[`${i}@${h}`];for(let rt of e.collectNonHarDependentModuleList(i))se.includes(`${rt}@${h}`)||se.push(`${rt}@${h}`);console.log(Eo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Ue=new mr(e.rootDir,t);await Ue.startWatchSession({moduleSpecs:se,productName:h});let nt=Ip(e,i,s,d,h);await xp(a,l,w,nt,S,!!n.uninstall),console.log(Eo("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.")),Ue.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function wb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=zc(e,n.module),{moduleName:i}=Vc(o[0]);Uc(n.module,i);let s=ne.from(t),a=await ds(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Cp(e,i,r);let d=[`${i}@${c}`],h=await Pp({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function vb(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(i)){o.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))o.add(c)}return[...o]}async function Np(n,e,t){let r=zc(e,n.module),o=r.map(Vc),i=ne.from(t);if(await Rp(n.device,i)){await mb(n,e,t,o,r);return}hb(e,o);let s=new xt(t),a=await ds(i,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 fb(e,t,o,l,d);let h=vb(e,o,c,l),w=e.getBundleName(),S=kp(e,o,n.ability);await xp(s,a,w,h,S,!!n.uninstall)}async function Sb(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(ls.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=ls.join(e.rootDir,".hvigor",r),i=ne.from(t),s=await ds(i,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new Zi(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(cs("[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(cs(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(cs("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Np(n,e,t)}var Lp=Jc;import{Command as bb}from"commander";import{green as Op,red as Mp,cyan as Yc}from"colorette";import{execa as _p}from"execa";function Eb(){return"
|
|
65
|
+
`+Eo("Build completed successfully."))}async function mb(n,e,t,r,o){let i=new xt(t),s=ne.from(t),a=r[0]?.moduleName||o[0];await Tp(n,e,t,i,s,a)}function hb(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}async function gb(n){let e=G.discover(process.cwd());console.warn(cs("Ensure the project source is trusted before proceeding."));let t=await I.new();if(n.skipBuild||t.assertJava(),n.hotreloadApply){await wb(n,e,t);return}if(n.hotreload){await yb(n,e,t);return}if(n.apply){await Sb(n,e,t);return}await Np(n,e,t)}async function yb(n,e,t){if(n.hotreload==="stop"){await Ap(t,e);return}let o=zc(e,n.module).map(Vc),{moduleName:i,targetName:s}=o[0];Uc(n.module,i);let a=new xt(t),c=ne.from(t),l=await ds(c,n.device),d=l.includes("127.0.0.1")||l.includes("localhost"),h=n.product||"default";e.validateProduct(h);let w=e.getBundleName(),S=kp(e,o,n.ability);es.generate(e.rootDir,i,h,t);let A=new xe(t,e.rootDir);console.log(Eo("Ensuring hvigor daemon is running (via --sync --daemon, no hap build)...")),await A.ensureDaemonRunning();let se=[`${i}@${h}`];for(let rt of e.collectNonHarDependentModuleList(i))se.includes(`${rt}@${h}`)||se.push(`${rt}@${h}`);console.log(Eo("Building hap + starting watch session (socket -> CommonBuild assembleHap --hot-reload-build --watch, kept open)..."));let Ue=new mr(e.rootDir,t);await Ue.startWatchSession({moduleSpecs:se,productName:h});let nt=Ip(e,i,s,d,h);await xp(a,l,w,nt,S,!!n.uninstall),console.log(Eo("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.")),Ue.onSocketDisconnect(()=>{console.log("Daemon disconnected (likely via --hotreload stop). Exiting watch session."),process.exit(0)}),await new Promise(()=>{})}async function wb(n,e,t){let r=n.hotreloadApply;if(!r)throw new Error("hotreload-apply requires --hotreload-apply <fileName> (under .hvigor/)");let o=zc(e,n.module),{moduleName:i}=Vc(o[0]);Uc(n.module,i);let s=ne.from(t),a=await ds(s,n.device),c=n.product||"default";e.validateProduct(c);let l=e.getBundleName();Cp(e,i,r);let d=[`${i}@${c}`],h=await Pp({applyFileName:r,projectPath:e.rootDir,moduleName:i,productName:c,bundleName:l,toolProvider:t,targetDeviceId:a,moduleSpecs:d});if(!h.success)throw new Error(h.message)}function vb(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e)for(let a of n.collectNonHarDependentModuleList(i)){o.add(n.findArtifactPath(a,s,t,r));for(let c of n.findRemoteHspPaths(a,s,r))o.add(c)}return[...o]}async function Np(n,e,t){let r=zc(e,n.module),o=r.map(Vc),i=ne.from(t);if(await Rp(n.device,i)){await mb(n,e,t,o,r);return}hb(e,o);let s=new xt(t),a=await ds(i,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 fb(e,t,o,l,d);let h=vb(e,o,c,l),w=e.getBundleName(),S=kp(e,o,n.ability);await xp(s,a,w,h,S,!!n.uninstall)}async function Sb(n,e,t){let r=n.apply;if(!r)throw new Error("apply requires --apply <fileName> (under .hvigor/)");if(ls.basename(r)!==r)throw new Error(`apply file must be a plain file name (under .hvigor/), got: ${r}`);let o=ls.join(e.rootDir,".hvigor",r),i=ne.from(t),s=await ds(i,n.device),a=n.product||"default";e.validateProduct(a);let c=e.getBundleName(),l=e.profile.modules.find(w=>e.getModuleType(w.name)==="entry")?.name,d=l?e.getMainAbility(l,n.ability):n.ability||"EntryAbility",h=new Zi(t,e.rootDir);try{await h.execute({applyFile:o,productName:a,targetDeviceId:s,bundleName:c,abilityName:d}),console.log(cs("[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(cs(`[Apply] \u5931\u8D25\uFF1A${w.message}`)),console.warn(cs("[Apply] \u81EA\u52A8\u56DE\u9000\u5230\u5168\u91CF devecocli run..."))}await Np(n,e,t)}var Lp=Jc;import{Command as bb}from"commander";import{green as Op,red as Mp,cyan as Yc}from"colorette";import{execa as _p}from"execa";function Eb(){return"stable"}function Pb(){return"@deveco-test/hmos-deveco-cli"}function Cb(){return"0.3.0"}var Ib=new bb("update").description("Update deveco-cli to latest").action(async()=>{let n=Pb(),e=Cb(),t=Eb();console.log(Yc("Checking for updates..."));try{let{stdout:r}=await _p("npm",["view",n,`dist-tags.${t}`]),o=r.trim();if(!o||o===e){console.log(Op(`
|
|
66
66
|
${n} is already up to date (v${e}, tag: ${t})`));return}console.log(Yc(`
|
|
67
67
|
New version found: ${o} (current: ${e})`)),console.log(Yc(`Updating ${n}...`)),await _p("npm",["install","-g",`${n}@${t}`],{stdio:"inherit"}),console.log(`
|
|
68
68
|
`+Op(`${n} updated successfully to version ${o}.`))}catch(r){let o=r;console.error(Mp(`Failed to update ${n}`)),o.message&&console.error(Mp(o.message)),process.exit(1)}}),Fp=Ib;import{Command as tE}from"commander";import{execa as ps}from"execa";function be(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Ab}from"child_process";var Db=2500;function Rb(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function Tb(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=d=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(d))}},l=setTimeout(a,Db);n.once("error",d=>c(d.message)),Rb(n,l,s,a,c,i)}function jp(n,e,t){return m(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Ab(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),Tb(s,i,r,o)})}import*as gr from"path";function kb(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function xb(n){let e=n.instancePath?.trim();if(e)return gr.dirname(gr.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gr.dirname(gr.normalize(t)).replace(/\\/g,"/"):""}function Nb(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function Hp(n,e){return e?[...n,"-bootmode",e]:n}function Lb(n,e,t){let r=[Hp(["-start",n],t)],o=xb(e);if(o)for(let i of Nb(e.imageRoot))r.push(Hp(["-hvd",n,"-path",o,...i],t));return kb(r)}async function $p(n,e,t,r){let o=new Error("No start strategy ran"),i=Lb(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function Kc(n){return(await ne.withHdcPath(n).listDevices()).map(t=>t.serial).filter(jn)}async function Xc(n){let e=await Kc(n);return e.length===0?[]:(await Promise.all(e.map(r=>Xi(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function Up(n,e){return(await Xc(n)).includes(e)}import*as wr from"path";import{existsSync as Ob,statSync as Mb}from"fs";function yr(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function _b(n){let e=yr(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function Fb(n){return yr(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function jb(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=wr.dirname(wr.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=wr.join(t,r.name);Ob(o)&&Mb(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function Hb(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Fb(t),o=yr(t,["deviceType","DeviceType","devicetype"]),i=yr(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:_b(t),path:yr(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yr(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function $b(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function Bp(n){let t=Hb(n)??$b(n);return jb(t),t}function Zc(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Ub(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Bb(n){if(!Ub(n))return null;let e=Zc(n,["osVersion","OsVersion","OSVersion"]),t=Zc(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=Zc(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function us(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=Bb(o);i&&r.push(i)}return r}catch{return[]}}function Wp(n){let t=us(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var Gp=/no images are available/i,Wb="7.0.0",Gb={foldable:["open","half-open","close"],"2in1_foldable":["open","vertical-open","half-open","close"],triplefold:["single","double","triple","left-folded-right-half-folded","left-half-folded-right-expanded","left-expanded-right-folded","left-half-folded-right-folded","left-expanded-right-half-folded","left-half-folded-right-half-folded"]};function ct(n){return n.normalize("NFKC").trim().toLowerCase()}function qb(n,e){let t=n.deviceType?.trim(),r=t?Gb[ct(t)]:void 0;if(!r)throw new Error(`Fold-state control is not supported for emulator "${n.name}" (device type: ${t||"unknown"}).`);if(!r.includes(e))throw new Error(`Fold state "${e}" is not supported by emulator "${n.name}" (device type: ${t}). Available states: ${r.join(", ")}.`)}function Vb(n){let e=n.message||"";return Gp.test(e)}function zb(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function Po(n,e){return`${n} ${e.join(" ")}`.trim()}function Jb(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 vr=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: ${Po(this.emulatorPath,e)}`),ps(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return jp(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Bp(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(be(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=be(e),o=t.find(a=>be(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await $p(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
@@ -1288,7 +1288,7 @@ Failed to create project.`)),console.error(Tl(t.message)),xl.exit(1)}}),xm=kC;im
|
|
|
1288
1288
|
\r
|
|
1289
1289
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this.buffer.indexOf(`\r
|
|
1290
1290
|
\r
|
|
1291
|
-
`);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),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(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),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 ln=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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 o=this.callbacks.get(e);if(o)o(t,r),this.callbacks.delete(e);else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),o(),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 Ms=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Rr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function D(n){return typeof n=="object"&&n!==null}var Bm=20*1e3,zC=30*1e3,_s=class{client;nextRequestId=1;stopOnce=null;callbacks=new Rr;requestCallbacks=new ln;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new cn(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,ze);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,o=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((i,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(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},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 Ms(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=zC){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}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 o=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${o}, 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 o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}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 o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){D(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Bm,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Bm}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[r]);return}this.broadcastToClients({jsonrpc:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Fs=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 Ml(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)}},Ml=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var JC={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"},YC={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={...JC,...YC},dn={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 KC(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function XC(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function ZC(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 js=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Rr;requestCallbacks=new ln;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new cn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.EXIT,params:{}}),dn.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:T,method:k.INITIALIZED,params:{editors:e}}),dn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),dn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!KC(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 i=t.textDocument.uri,s=st(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!XC(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method: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:T,method:k.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),dn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=st(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Fs(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,k.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),dn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=st(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:T,method:k.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),dn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=st(e);f.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.DID_CLOSE,params:{textDocument:{uri:r}}}),dn.DID_CLOSE)}getDiagnosticMessage(e){let t=st(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 o of t)this.finalizeDiagnostic(o,k.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,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: ${ZC(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:T,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 o=r.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,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 o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(Wm)&&this.finalizeDiagnostic(t,k.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import qo from"path";import*as qs from"path";var Hs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var $s=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Us=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Bs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ws=class{typeSetting=new Us;parameterNames=new Bs};var Gs=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=U(qs.dirname(t)),this.indexingDataLocation=U(o),this.loggerPath=U(qs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Hs;gutterIconsSetting=new $s;inlayHintsSetting=new Ws;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Gm from"path";var Uo=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(Gm.join(e,"src","main","resources")))}};var QC="OS",Tr=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${QC}`;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 Uo(e)):this.buildProfileParam=new Uo}toString(){return JSON.stringify(this)}};var kr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as Lr from"fs";var Vs=class{modulePath;dependencies={};dynamicDependencies={}};var Vn=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var xr=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 Ut from"path";import*as zs from"fs";var Nr=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:it.OH_PACKAGE_JSON5},Bo=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,zn=`${L.DEPENDENCY}${L.JSON5}`,xW=it.SYNC_OUTPUT_PATH;var Wo=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Ut.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=We(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 o=e[t];if(!D(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Nr;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Ut.normalize(Ut.join(this.modulePath,L.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Ut.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Ut.resolve(this.modulePath,s)),zs.existsSync(i)&&zs.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as Go from"fs";import*as un from"path";import eI from"json5";var Js=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return un.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Go.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Go.readFileSync(e,"utf8"),r=eI.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!D(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,L.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,L.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,L.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;for(let[r,o]of Object.entries(e)){if(!D(o)){f.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];for(let[o,i]of Object.entries(e))if(D(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!D(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!D(s))return[];for(let[a,c]of Object.entries(s)){if(!D(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new Nr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=un.resolve(this.projectPath,un.join(t,L.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=un.isAbsolute(a)?a:un.resolve(this.projectPath,a);Go.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function qm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Jn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new kt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,Bo),o=Re.join(r,zn);if(!Lr.existsSync(r)||!Lr.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new xr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return 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];qm(l)&&(this.parseSingleModule(l,r,i,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,o=Re.join(r,Bo),i=Re.join(o,zn);if(!Lr.existsSync(o)||!Lr.existsSync(i))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 xr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,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(!qm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Re.resolve(this.projectPath,l.srcPath),w=Re.join(o,d),S=U(h),A=this.buildModuleDependencies(d,S,w,a);A.moduleName=d,t.push(A)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,i),c=U(s),l=new Tr(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new kr(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new xr(this.projectPath,e,t);Wo.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Vs;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new Vn(i);for(let i of e.finalDynamicDependencies)o[i.name]=new Vn(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Re.join(e,L.OH_PACKAGE_JSON5);if(!Lr.existsSync(r))return;Wo.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 Js(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),o=We(r);if(!D(o)||!D(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}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=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=We(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=We(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[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Re.join(this.projectPath,"build-profile.json5");this.buildProfileCache=We(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}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 Ys=class{constructor(e=[]){this.valueSet=e}valueSet};var Or=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Vm=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(Vm||{}),zm=()=>Object.values(Vm).filter(n=>typeof n=="number");var Ks=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Xs=class{applyEdit=!0;workspaceEdit=new Ks;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ys(zm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Or;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Zs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Qs=class{constructor(e=[]){this.valueSet=e}valueSet};var ea=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Jm=(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))(Jm||{}),Ym=()=>Object.values(Jm).filter(n=>typeof n=="number");var ta=class{completionItemKind=new Qs(Ym());completionItem=new ea;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var na=class{synchronization=new Zs;completion=new ta;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 Or;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var ra=class{workspace=new Xs;textDocument=new na;notebookDocument=null;window=null;general=null;experimental=null};var oa=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ia=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?qo.resolve(qo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=qu(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new _s(t):new js(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=st(this.rootUri),i=new Gs(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Jn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Yi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new oa(o,i,new ra),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,ze),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",ze),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}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 o=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:T,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}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 Jn(this.rootUri,this.sdkPath),o=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,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),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(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,h)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new Vn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Tr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new kr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=cr(qo.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=cr(qo.join(t,"default/openharmony/ets/api")),i=cr(qo.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!$m(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 Bt from"fs";import*as Oe from"path";import{createHash as nI}from"crypto";import{EventEmitter as rI}from"events";var sa=class extends rI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Bt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Bt.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 o of t){let i=Oe.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=Oe.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=Oe.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=Oe.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=We(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Oe.join(this.projectRoot,L.OH_PACKAGE_JSON5);Bt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Oe.resolve(this.projectRoot,i.srcPath),a=Oe.join(s,L.OH_PACKAGE_JSON5);Bt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Oe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Bt.readFileSync(t,"utf-8");return nI("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let o=Bt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Oe.basename(t),relativePath:Oe.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as pn from"fs";import*as ut from"path";import{createHash as oI}from"crypto";import{EventEmitter as iI}from"events";var aa=class extends iI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ut.join(t,Bo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!pn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=pn.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(ut.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===L.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===zn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ut.join(this.depMapDir,r);pn.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=ut.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=ut.join(this.depMapDir,zn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:ut.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!pn.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=ut.join(this.depMapDir,zn);try{let r=We(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return 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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return U(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=ut.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,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=ut.join(this.depMapDir,i,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=pn.readFileSync(t,"utf-8");return oI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as sI}from"child_process";var aI=["install","--all"];async function cI(n,e,t,r){return new Promise(o=>{let i=sI(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1291
|
+
`);if(r===-1)break;let i=this.buffer.slice(0,r).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!i){f.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(r+4);continue}let s=parseInt(i[1],10),a=r+4,c=a+s;if(this.buffer.length<c)break;let l=this.buffer.slice(a,c).toString("utf8"),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(o=>{let i=!1,s=()=>{i||(i=!0,clearTimeout(c),r.off("exit",a),o())},a=()=>s();r.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let r=t.search(/\S/);if(r<0||t[r]!=="{"&&t[r]!=="[")return null;let o=0,i=!1,s=!1;for(let a=r;a<t.length;a++){let c=t[a];if(i){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(i=!1);continue}if(c==='"'){i=!0;continue}if(c==="{"||c==="["){o++;continue}if((c==="}"||c==="]")&&(o--,o===0)){let l=t.slice(r,a+1),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 ln=class{callbacks=new Map;pending=new Map;timeouts=new Map;registerPending(e,t,r){return new Promise((o,i)=>{let s;r>0&&(s=setTimeout(()=>{this.pending.delete(e),this.timeouts.delete(e),i(new Error(`LSP request '${t}' (id=${e}) timeout after ${r}ms`))},r),this.timeouts.set(e,s)),this.pending.set(e,{resolve:o,reject:i,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 o=this.callbacks.get(e);if(o)o(t,r),this.callbacks.delete(e);else{let i=[...this.callbacks.keys()].map(s=>String(s));f.info(`[RequestCallbackManager] emit: NO callback for key='${e}', registered keys=[${i.join(",")}]`)}}registerTimeout(e,t,r,o){let i=this.timeouts.get(e);i&&clearTimeout(i);let s=setTimeout(()=>{f.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),o(),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 Ms=class{uri;diagnostics=[];constructor(e){this.uri=e}set(e){this.diagnostics=e}get(){return this.diagnostics}clear(){this.diagnostics=[]}};var Rr=class{map=new Map;register(e,t){let r=this.map.get(e);r||(r=new Set,this.map.set(e,r)),r.add(t)}unregister(e,t){let r=this.map.get(e);r&&(t!==void 0?r.delete(t):r.clear(),r.size===0&&this.map.delete(e))}invoke(e,...t){let r=this.map.get(e);if(r)for(let o of r)try{o(...t)}catch(i){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,i)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function D(n){return typeof n=="object"&&n!==null}var Bm=20*1e3,zC=30*1e3,_s=class{client;nextRequestId=1;stopOnce=null;callbacks=new Rr;requestCallbacks=new ln;diagnosticMap=new Map;initProgressReset=null;constructor(e){this.client=new cn(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,ze);return this.client.sendRequest(y.INITIALIZE,e,t),r}sendInitializeResettable(e,t){let r=this.nextRequestId++,o=this.requestCallbacks.registerPending(r,y.INITIALIZE,0);return this.client.sendRequest(y.INITIALIZE,e,r),new Promise((i,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(),o.then(()=>{clearTimeout(a),this.initProgressReset=null,i()},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 Ms(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=zC){let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}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 o=r instanceof Error?r.message:String(r);f.error(`[LSP] JSON parse error: ${o}, 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 o=new Error(`LSP error ${e.error.code}: ${e.error.message}`);this.requestCallbacks.rejectPending(r,o)}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 o=e.diagnostics||[];this.normalizeDiagnostics(o),r.set(o),this.finalizeDiagnostic(t,o)}normalizeDiagnostics(e){for(let t of e)if(t.severity!==void 0){let r={1:"Error",2:"Warning",3:"Information",4:"Hint"};t.severityStr=r[t.severity]||"Unknown"}}handleProgress(e){D(e)&&this.broadcastToClients({jsonrpc:T,method:y.PROGRESS,params:e})}registerDiagnosticTimeout(e){this.requestCallbacks.registerTimeout(e,y.PUBLISH_DIAGNOSTICS,Bm,()=>{let t=this.diagnosticMap.get(e),r=t?t.get():[];this.finalizeDiagnostic(e,r,r.length>0?void 0:`received no diagnostics within ${Bm}ms, uri: ${e}`)})}finalizeDiagnostic(e,t,r){let o={uri:e,diagnostics:t,...r?{errorMessage:r}:{}};this.requestCallbacks.emit(e,y.PUBLISH_DIAGNOSTICS,o),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 o of t)this.finalizeDiagnostic(o,[r]);return}this.broadcastToClients({jsonrpc:T,method:y.ARKTS_ERROR,params:{message:e.message}})}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};var Fs=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 Ml(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)}},Ml=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var JC={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"},YC={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={...JC,...YC},dn={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 KC(n){if(!D(n))return!1;let e=n.textDocument;return D(e)&&typeof e.uri=="string"}function XC(n){return D(n)?typeof n.uri=="string"&&typeof n.type=="number":!1}function ZC(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 js=class n{client;isInitialized=!1;stopOnce=null;callbacks=new Rr;requestCallbacks=new ln;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;constructor(e){this.client=new cn(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(e){await this.client.start(e)}stop(){return this.stopOnce||(this.stopOnce=(async()=>{f.info("[LegacyClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.EXIT,params:{}}),dn.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:T,method:k.INITIALIZED,params:{editors:e}}),dn.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:T,id:0,result:{}}),dn.EMPTY)}sendAsyncRequest(e,t,r,o){if(!D(t)){f.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!KC(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 i=t.textDocument.uri,s=st(i);t.textDocument.uri=s,delete t.requestId;let a=o??e;f.info(`[LSP] sendAsyncRequest ${a}, filePath: ${i}`),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:e,params:{params:t,requestId:r}}),a)}onDidChangeWatchedFiles(e){if(f.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let r of e){if(!XC(r)){f.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(r)}`);continue}t.push(r)}this.client.sendRaw(JSON.stringify({jsonrpc:T,method: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:T,method:k.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),dn.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,r=t.split(".").pop()||"";if(r!=="ets"&&r!=="ts")return;let o=st(t);e.textDocument.uri=o,f.info(`[LSP] onAsyncOpenFile, uri: ${o}`);let i=this.diagnosticMap.get(o);i||(i=new Fs(o),this.diagnosticMap.set(o,i),this.registerDiagnosticTimeout(o,k.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(i.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),dn.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=st(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:T,method:k.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),dn.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let r=st(e);f.info(`[LSP] didClose, uri: ${r}`);let o=this.diagnosticMap.get(r);if(!t&&(!o||o.isFromEditor)){f.info(`[LSP] closeFile skip, !diagnostic: ${!o}, isFromEditor: ${o?.isFromEditor}`);return}this.cleanupDiagnosticState(r),this.client.sendRaw(JSON.stringify({jsonrpc:T,method:k.DID_CLOSE,params:{textDocument:{uri:r}}}),dn.DID_CLOSE)}getDiagnosticMessage(e){let t=st(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 o of t)this.finalizeDiagnostic(o,k.PUBLISH_DIAGNOSTICS,[r]);return}this.broadcastToClients({jsonrpc:T,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: ${ZC(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:T,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 o=r.requestId;if(typeof o!="number"){f.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(o,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 o=this.diagnosticMap.get(t);if(!o){f.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let i=e.diagnostics||[];i.length!==0?i.forEach(s=>{this.normalizeDiagnostic(s),o.addMessage(r,JSON.stringify(s))}):o.setReceivedType(r),o.hasReceivedAllTypes(Wm)&&this.finalizeDiagnostic(t,k.PUBLISH_DIAGNOSTICS,o.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),i={1:"Error",2:"Warning",3:"Information",4:"Hint"}[r]||"Unknown";t.severityStr=i,t.severity=i}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let r=e[t];r&&typeof r.line=="number"&&(r.line=r.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,n.DIAGNOSTIC_TIMEOUT_MS,()=>{let r=this.diagnosticMap.get(e),o=r?r.getMessages():[];this.finalizeDiagnostic(e,t,o,o.length>0?void 0:`received no diagnostics within ${n.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,r,o){let i={uri:e,diagnostics:r,...o?{errorMessage:o}:{}};this.requestCallbacks.emit(e,t,i),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import qo from"path";import*as qs from"path";var Hs=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var $s=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var Us=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var Bs=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var Ws=class{typeSetting=new Us;parameterNames=new Bs};var Gs=class{constructor(e,t,r,o){this.rootUri=e;this.lspServerWorkspacePath=U(qs.dirname(t)),this.indexingDataLocation=U(o),this.loggerPath=U(qs.join(r,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new Hs;gutterIconsSetting=new $s;inlayHintsSetting=new Ws;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Gm from"path";var Uo=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(Gm.join(e,"src","main","resources")))}};var QC="OS",Tr=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${QC}`;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 Uo(e)):this.buildProfileParam=new Uo}toString(){return JSON.stringify(this)}};var kr=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as Re from"path";import*as Lr from"fs";var Vs=class{modulePath;dependencies={};dynamicDependencies={}};var Vn=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var xr=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 Ut from"path";import*as zs from"fs";var Nr=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:it.OH_PACKAGE_JSON5},Bo=`${L.HVIGOR_CACHE}/${L.DEPENDENCY}`,zn=`${L.DEPENDENCY}${L.JSON5}`,NW=it.SYNC_OUTPUT_PATH;var Wo=class n{dependencyPath;modulePath;projectPath;static FILE_DEPENDENCY_PREFIX="file:";static PARAMETER_PREFIX="@param:";fileSpecPattern;fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;static PACKAGE_JSON_PARSER_MAP=new Map;dependencies=[];devDependencies=[];dynamicDependencies=[];static getInstance(e,t,r){let o=this.PACKAGE_JSON_PARSER_MAP.get(e);return o||(o=new n(e,t,r),this.PACKAGE_JSON_PARSER_MAP.set(e,o)),o}constructor(e,t,r){this.dependencyPath=e,this.modulePath=t,this.projectPath=r,this.fileSpecPattern=n.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=Ut.join(this.dependencyPath,L.OH_PACKAGE_JSON5),r=We(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 o=e[t];if(!D(o))return r;for(let[i,s]of Object.entries(o)){if(typeof s!="string"){f.error(`${i} package dependency value is not String ${t}`);continue}let a=new Nr;a.name=i;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(n.PARAMETER_PREFIX)||this.parseDependencyPath(i,c,a,!1),r.push(a)}return r}parseDependencyPath(e,t,r,o){if(!(!e||!t))try{let i=Ut.normalize(Ut.join(this.modulePath,L.OH_MODULES_PATH,e));if(!(t.startsWith(n.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){r.dependencyPath=i;return}if(r.path=t,this.fileNameForOhpm.test(t)){r.dependencyPath=i;return}let s=t;if(t.startsWith(n.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(n.FILE_DEPENDENCY_PREFIX.length)),Ut.isAbsolute(s)){r.dependencyPath=i;return}o||(i=Ut.resolve(this.modulePath,s)),zs.existsSync(i)&&zs.statSync(i).isDirectory()&&(r.dependencyPath=i)}catch(i){f.error("parser dependency path is invalid",i)}}};import*as Go from"fs";import*as un from"path";import eI from"json5";var Js=class n{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;lockFileCache=null;lockFileParsed=!1;constructor(e=""){this.projectPath=e}parseDependencies(e){if(!this.ensureLockFileParsed())return!1;let t=this.lockFileCache;return this.extractDependencies(t.modules,t.storePathMap,e),!0}ensureLockFileParsed(){if(this.lockFileParsed)return this.lockFileCache!==null;this.lockFileParsed=!0;let e=this.getLockFilePath(),t=this.readLockFile(e);if(!t)return!1;let r=this.validateLockFile(t);return r.valid?(this.lockFileCache={modules:r.modules,storePathMap:this.parseStorePathMap(r.packages)},!0):!1}getLockFilePath(){return un.join(this.projectPath,L.OH_MODULES_PATH,L.OHPM_PATH,L.LOCK_JSON5_FILE)}readLockFile(e){if(!Go.existsSync(e))return f.error("lock file does not exist"),this.clearDependencies(),null;try{let t=Go.readFileSync(e,"utf8"),r=eI.parse(t);return r||(f.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return f.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!D(e))return f.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return f.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let r=e.packages;return r?{valid:!0,modules:t,packages:r}:(f.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,r){this.storePathMap=t,this.finalDependencies=this.getDependencyList(e,L.KEY_DEPENDENCY,r),this.finalDevDependencies=this.getDependencyList(e,L.KEY_DEV_DEPENDENCY,r),this.finalDynamicDependencies=this.getDependencyList(e,L.KEY_DYNAMIC_DEPENDENCY,r)}parseStorePathMap(e){let t=new Map;if(!D(e))return t;for(let[r,o]of Object.entries(e)){if(!D(o)){f.error(`${r} value is not json object`);continue}typeof o.storePath=="string"&&t.set(r,o.storePath)}return t}getDependencyList(e,t,r){if(!D(e))return[];for(let[o,i]of Object.entries(e))if(D(i)){let s=typeof i.name=="string"?i.name:"";if(r==="."&&s===""||s===r)return this.getFinalDependencyList(e,t,o)}return[]}getFinalDependencyList(e,t,r){let o=e[r];if(!D(o))return f.error("moduleJsonObject is null"),[];let i=[],s=o[t];if(!D(s))return[];for(let[a,c]of Object.entries(s)){if(!D(c))continue;let l=typeof c.specifier=="string"?c.specifier:"",d=typeof c.version=="string"?c.version:"",h=new Nr;h.name=a,h.version=d.startsWith(n.FILE_DEPENDENCY_PREFIX)?d.substring(n.FILE_DEPENDENCY_PREFIX.length):d,this.parseDependencyPath(h,r,a,l,d);let w=`${a}@${d}`;this.storePathMap.has(w)&&(h.storePath=this.storePathMap.get(w)||""),i.push(h)}return i}parseDependencyPath(e,t,r,o,i){let s=un.resolve(this.projectPath,un.join(t,L.OH_MODULES_PATH,r));try{let a=i.startsWith(n.FILE_DEPENDENCY_PREFIX)?i.substring(n.FILE_DEPENDENCY_PREFIX.length):i,c=un.isAbsolute(a)?a:un.resolve(this.projectPath,a);Go.existsSync(c)?(e.path=o,e.dependencyPath=this.fileNameForOhpm.test(i)?s:c):e.dependencyPath=s}catch(a){f.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};function qm(n){return D(n)?typeof n.name=="string"&&typeof n.srcPath=="string":!1}var Jn=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new kt(this.projectPath)}projectPath;sdkPath;moduleInfoParse;lockJson5Parser=null;sdkPkgCache=void 0;buildProfileCache=void 0;getAllDependencyMap(e){let t=this.projectPath,r=Re.join(t,Bo),o=Re.join(r,zn);if(!Lr.existsSync(r)||!Lr.existsSync(o)){let c="Dependency map or JSON not found";return f.warn(`[Parser] getAllDependencyMap failed: ${c}.`),{status:"ERROR",message:`${c}, please rebuild project`}}let i=new xr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(r,i),this.parseLockJson(i);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let c="No modules found in build-profile.json5";return 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];qm(l)&&(this.parseSingleModule(l,r,i,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,o=Re.join(r,Bo),i=Re.join(o,zn);if(!Lr.existsSync(o)||!Lr.existsSync(i))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 xr(this.projectPath,".",this.projectPath);this.parseProjectDependencies(o,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(!qm(l))continue;let d=l.name;if(s&&!s.has(d))continue;let h=Re.resolve(this.projectPath,l.srcPath),w=Re.join(o,d),S=U(h),A=this.buildModuleDependencies(d,S,w,a);A.moduleName=d,t.push(A)}return t}parseSingleModule(e,t,r,o){let i=e.name,s=Re.resolve(this.projectPath,e.srcPath),a=Re.join(t,i),c=U(s),l=new Tr(c),d=this.buildModuleDependencies(i,c,a,r);this.parseModuleJson5(c,l);let h=this.parseMainPages(c);this.parseSdkJson(l),this.parseCompatibleSdkVersion(l),l.moduleName=i,l.moduleType=i,l.packageName=i,l.moduleDependencies=d,l.moduleJsonParam=new kr(h),o.push(l)}buildModuleDependencies(e,t,r,o){let i=new xr(this.projectPath,e,t);Wo.getInstance(r,t,this.projectPath).parseDependency(i),this.parseLockJson(i),i.finalDependencies.push(...o.finalDependencies),i.finalDevDependencies.push(...o.finalDevDependencies),i.finalDynamicDependencies.push(...o.finalDynamicDependencies),i.finalDependencies.push(...i.finalDevDependencies);let a=new Vs;return a.modulePath=t,this.toModuleDependencies(i,a),a}toModuleDependencies(e,t){let r={},o={};for(let i of e.finalDependencies)r[i.name]=new Vn(i);for(let i of e.finalDynamicDependencies)o[i.name]=new Vn(i);t.dependencies=r,t.dynamicDependencies=o}parseProjectDependencies(e,t){let r=Re.join(e,L.OH_PACKAGE_JSON5);if(!Lr.existsSync(r))return;Wo.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 Js(this.projectPath)),this.lockJson5Parser}parseModuleJson5(e,t){let r=Re.join(e,"src","main","module.json5"),o=We(r);if(!D(o)||!D(o.module))return;let i=o.module;t.permissions=this.parseRequestPermissions(i),t.deviceType=this.parseDeviceTypes(i)}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=Re.join(e,"src","main","resources","base","profile","main_pages.json"),r=We(t);return!D(r)||!Array.isArray(r.src)?[]:r.src.filter(o=>typeof o=="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=Re.join(this.sdkPath,"default","sdk-pkg.json");this.sdkPkgCache=We(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[o,i]=this.parseBySplit(r.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=i}getBuildProfile(){if(this.buildProfileCache===void 0){let e=Re.join(this.projectPath,"build-profile.json5");this.buildProfileCache=We(e)}return this.buildProfileCache}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,e];let r=e.substring(0,t),o=e.substring(t+1,e.length-1);return[r,o]}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 Ys=class{constructor(e=[]){this.valueSet=e}valueSet};var Or=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Vm=(P=>(P[P.File=1]="File",P[P.Module=2]="Module",P[P.Namespace=3]="Namespace",P[P.Package=4]="Package",P[P.Class=5]="Class",P[P.Method=6]="Method",P[P.Property=7]="Property",P[P.Field=8]="Field",P[P.Constructor=9]="Constructor",P[P.Enum=10]="Enum",P[P.Interface=11]="Interface",P[P.Function=12]="Function",P[P.Variable=13]="Variable",P[P.Constant=14]="Constant",P[P.String=15]="String",P[P.Number=16]="Number",P[P.Boolean=17]="Boolean",P[P.Array=18]="Array",P[P.Object=19]="Object",P[P.Key=20]="Key",P[P.Null=21]="Null",P[P.EnumMember=22]="EnumMember",P[P.Struct=23]="Struct",P[P.Event=24]="Event",P[P.Operator=25]="Operator",P[P.TypeParameter=26]="TypeParameter",P))(Vm||{}),zm=()=>Object.values(Vm).filter(n=>typeof n=="number");var Ks=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var Xs=class{applyEdit=!0;workspaceEdit=new Ks;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new Ys(zm());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new Or;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var Zs=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Qs=class{constructor(e=[]){this.valueSet=e}valueSet};var ea=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var Jm=(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))(Jm||{}),Ym=()=>Object.values(Jm).filter(n=>typeof n=="number");var ta=class{completionItemKind=new Qs(Ym());completionItem=new ea;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var na=class{synchronization=new Zs;completion=new ta;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 Or;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var ra=class{workspace=new Xs;textDocument=new na;notebookDocument=null;window=null;general=null;experimental=null};var oa=class{constructor(e,t,r){this.rootUri=e;this.initializationOptions=t;this.capabilities=r}rootUri;initializationOptions;capabilities};var ia=class{messageHandle;get stdHandle(){return this.messageHandle}get legacyHandle(){return this.messageHandle}onAsyncOpenFile(e){this.legacyHandle.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.legacyHandle.closeFile(e,t)}serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];sdkPath;rootUri;nodeMaxOldSpaceSize;nodePath;useStandardProtocol;get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}constructor(e){this.sdkPath=e.sdkPath,this.rootUri=e.workspaceRoot,this.nodeMaxOldSpaceSize=e.nodeMaxOldSpaceSize,this.nodePath=e.nodePath,this.useStandardProtocol=e.useStandardProtocol,this.serverPath=e.useStandardProtocol?qo.resolve(qo.dirname(e.arktsLangServerPath),"standardIndex","index.js"):e.arktsLangServerPath,this.logPath=qu(),this.indexLogPath=e.indexLogPath||this.logPath;let t={serverPath:this.serverPath,logPath:this.logPath,indexingDataLocation:this.indexLogPath,nodePath:this.nodePath};this.messageHandle=e.useStandardProtocol?new _s(t):new js(t),this.messageHandle.setBroadcastToClients(r=>this.onLspMessage(r))}async start(e,t){let r=!1;try{f.info(`serverPath: ${this.serverPath}`),f.info(`rootUri: ${this.rootUri}`),f.info(`sdkPath: ${this.sdkPath}`),f.info(`logPath: ${this.logPath}`);let o=st(this.rootUri),i=new Gs(o,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Jn(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),i.modules=s;let l=Yi(s.length,this.nodeMaxOldSpaceSize);if(await this.messageHandle.start(l),this.currentParams=new oa(o,i,new ra),this.useStandardProtocol){let d=this.messageHandle;await d.sendInitializeResettable(this.currentParams,ze),f.info("[LSP] initialize response received"),d.broadcastToClients({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}}),d.sendInitialized()}else await this.startLegacy(this.currentParams,e);r=!0}catch(o){this.lastStartErrorMessage=o instanceof Error?o.message:String(o),f.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(r)}async startLegacy(e,t){let r=this.messageHandle;r.sendInitialize(e,1),r.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:T,method:y.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((o,i)=>{r.onIndexingProgressUpdate(i),r.onInitializationCompleted(o)},"LSP initialization",ze),r.sendInitialized(t)}withResettableTimeout(e,t,r){return new Promise((o,i)=>{let s,a=()=>{s=setTimeout(()=>{i(new Error(`${t} timeout after ${r}ms`))},r)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),o()},c)})}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 o=D(r)?r:{};f.info(`[LSP] onDiagnosticCompleted called, uri: ${e}`);let i={jsonrpc:T,method:t,params:{uri:typeof o.uri=="string"?o.uri:e,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics:[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(i)})}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 Jn(this.rootUri,this.sdkPath),o=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,o);return this.applyModuleModelsUpdate(d),this.sendDidChangeConfiguration({moduleSet:d}),f.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${d.length}`),this.lastDepsOnlyForDiff=l,l}let i=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(i.length===0&&s.size===0)return f.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];f.info(`[LspServerProxy] Module-level deps changed, parsing: [${i.join(", ")}]`);let a=r.getDependenciesOnly(i);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),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(o=>[o.moduleName??"",o]));for(let o of e){let i=o.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(i,t,r),c=o.dependencies??{},l=o.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(d,h)=>{(o.dependencies??={})[d]=this.makeDeleteEntry(d,h)}),this.markAddAndDeleteInDeps(a,l,(d,h)=>{(o.dynamicDependencies??={})[d]=this.makeDeleteEntry(d,h)})}}getOldDepsForModule(e,t,r){let o=t.get(e),i=o?.moduleDependencies?.dependencies??{},s=o?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(i).length===0&&Object.keys(s).length===0){let a=r.get(e);a&&(i=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:i,oldDynamic:s}}markAddAndDeleteInDeps(e,t,r){for(let o of Object.keys(t))o in e||(t[o].type="add");for(let o of Object.keys(e))o in t||r(o,e[o])}makeDeleteEntry(e,t){return new Vn({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Tr(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new kr([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let r=[];for(let o of e){let i=o.moduleName??"",s=t.get(i);s?(s.modulePath=o.modulePath,s.moduleDependencies=o):s=this.createMinimalModelFromDepsItem(o),r.push(s)}return r}mergeIncrementalDeps(e,t,r){let o=new Map(r.map(s=>[s.moduleName??"",s])),i=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=o.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,o.delete(a)),i.push(s)}for(let[,s]of o)i.push(this.createMinimalModelFromDepsItem(s));return i}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,r=cr(qo.join(t,"default/openharmony/ets/build-tools/ets-loader")),o=cr(qo.join(t,"default/openharmony/ets/api")),i=cr(qo.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=r,s.sdkJsPath=o,s.hosSdkPath=i}sendRequest(e){switch(e.method){case y.HOVER:this.stdHandle.sendLspRequest(y.HOVER,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.DEFINITION:this.stdHandle.sendLspRequest(y.DEFINITION,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;case y.REFERENCES:this.stdHandle.sendLspRequest(y.REFERENCES,e.params).then(t=>this.onLspMessage({jsonrpc:T,id:e.id,result:t}),t=>this.onLspMessage({jsonrpc:T,id:e.id,error:{code:-32603,message:t.message}}));break;default:f.warn(`Unhandled LSP request: ${e.method}`)}}sendNotification(e){if(!$m(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 Bt from"fs";import*as Oe from"path";import{createHash as nI}from"crypto";import{EventEmitter as rI}from"events";var sa=class extends rI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r}projectRoot;watchers=new Map;debounceTimers=new Map;contentHashes=new Map;buildProfileWatcher=null;lastModulesSnapshot="";lastModules=[];debounceMs;start(){let t=this.parseModulesFromBuildProfile();this.lastModules=t,this.lastModulesSnapshot=this.computeModulesSnapshot(t),this.refreshWatchTargets(),this.watchBuildProfile()}refreshWatchTargets(){let t=new Set(this.collectWatchTargets()),r=new Set(this.watchers.keys());for(let o of t)r.has(o)||this.watchFile(o);for(let o of r)t.has(o)||(this.unwatchFile(o),f.info(`[ConfigFileWatcher] Stopped watching: ${o}`));f.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!Bt.existsSync(t)){f.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=Bt.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 o of t){let i=Oe.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:i,relativePath:o.srcPath,timestamp:r,moduleName:o.name})}}emitModuleRemovedEvents(t,r){for(let o of t){let i=Oe.resolve(this.projectRoot,o.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:i,relativePath:o.srcPath,timestamp:r,removedModuleName:o.name})}}emitModuleRenamedEvents(t,r){for(let o of t){let i=Oe.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name,removedModuleName:o.before.name})}}emitModuleMovedEvents(t,r){for(let o of t){let i=Oe.resolve(this.projectRoot,o.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:i,relativePath:o.after.srcPath,timestamp:r,moduleName:o.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let r=Date.now();this.emitModuleAddedEvents(t.added,r),this.emitModuleRemovedEvents(t.removed,r),this.emitModuleRenamedEvents(t.renamed,r),this.emitModuleMovedEvents(t.moved,r)}onBuildProfileChanged(){let t="__build_profile__",r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(i);if(s===this.lastModulesSnapshot){f.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,i);this.lastModules=i,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,o)}computeModulesSnapshot(t){return t.map(o=>`${o.name}::${o.srcPath}`).sort().join("|")}diffModules(t,r){let o=this.buildModuleMatchState(r),i={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,o),this.matchRenamedModules(t,o,i),this.matchMovedModules(t,o,i),this.collectRemovedModules(t,o,i),this.collectAddedModules(r,o,i),i}buildModuleMatchState(t){let r=new Map,o=new Map;for(let i of t)r.set(i.srcPath,i),o.set(i.name,i);return{matchedOld:new Set,matchedNew:new Set,newBySrc:r,newByName:o}}matchExactModules(t,r){for(let o of t){let i=r.newBySrc.get(o.srcPath);i&&i.name===o.name&&(r.matchedOld.add(o),r.matchedNew.add(i))}}matchRenamedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newBySrc.get(i.srcPath);s&&!r.matchedNew.has(s)&&s.name!==i.name&&(o.renamed.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}matchMovedModules(t,r,o){for(let i of t){if(r.matchedOld.has(i))continue;let s=r.newByName.get(i.name);s&&!r.matchedNew.has(s)&&s.srcPath!==i.srcPath&&(o.moved.push({before:i,after:s}),r.matchedOld.add(i),r.matchedNew.add(s))}}collectRemovedModules(t,r,o){for(let i of t)r.matchedOld.has(i)||o.removed.push(i)}collectAddedModules(t,r,o){for(let i of t)r.matchedNew.has(i)||o.added.push(i)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let r=We(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return f.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${r instanceof Error?r.message:String(r)}`),[]}}collectWatchTargets(){let t=[],r=Oe.join(this.projectRoot,L.OH_PACKAGE_JSON5);Bt.existsSync(r)&&t.push(r);let o=this.parseModulesFromBuildProfile();for(let i of o){let s=Oe.resolve(this.projectRoot,i.srcPath),a=Oe.join(s,L.OH_PACKAGE_JSON5);Bt.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return Oe.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let r=Bt.readFileSync(t,"utf-8");return nI("sha256").update(r).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let r=this.computeFileHash(t);r&&this.contentHashes.set(t,r);let o=Bt.watch(t,i=>{i==="change"&&this.onFileChanged(t)});o.on("error",i=>{f.error(`[ConfigFileWatcher] Watch error for ${t}: ${i.message}`)}),this.watchers.set(t,o)}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 o=this.debounceTimers.get(t);o&&(clearTimeout(o),this.debounceTimers.delete(t))}onFileChanged(t){let r=this.debounceTimers.get(t);r&&clearTimeout(r);let o=setTimeout(()=>{this.debounceTimers.delete(t);let i=this.computeFileHash(t);if(!i){f.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===i){f.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,i),f.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:Oe.basename(t),relativePath:Oe.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,o)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),f.info("[ConfigFileWatcher] All watchers stopped")}};import*as pn from"fs";import*as ut from"path";import{createHash as oI}from"crypto";import{EventEmitter as iI}from"events";var aa=class extends iI{constructor(t,r=500){super();this.projectRoot=t;this.debounceMs=r,this.coalesceMs=r+300,this.depMapDir=ut.join(t,Bo)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!pn.existsSync(this.depMapDir)){f.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=pn.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(ut.resolve(t))}onDirEvent(t,r){if(!r||typeof r!="string")return;let o=r.replace(/\\/g,"/"),i;if(o===L.OH_PACKAGE_JSON5)i="root-oh-package";else if(o===zn)i="dep-map-json";else{let a=o.match(/^([^/]+)\/oh-package\.json5$/);i=a?`module:${a[1]}`:""}if(!i)return;let s=ut.join(this.depMapDir,r);pn.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=ut.join(this.depMapDir,L.OH_PACKAGE_JSON5),r=ut.join(this.depMapDir,zn),o=this.parseModulesFromDepMap(),i=[{path:t,tag:"root-oh-package"},{path:r,tag:"dep-map-json"},...o.map(s=>({path:ut.join(this.depMapDir,s.name,L.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of i){if(!pn.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=ut.join(this.depMapDir,zn);try{let r=We(t);if(typeof r!="object"||r===null)return[];let o=r.modules;return Array.isArray(o)?o.filter(i=>{if(typeof i!="object"||i===null)return!1;let s=i;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(r){return 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,o,i){for(let s of t)s.startsWith("module:")?(o.add(s.substring(7)),r.add("moduleDepsChanged")):s.startsWith("dep-added:")?(o.add(s.substring(10)),r.add("moduleAdded")):s.startsWith("dep-removed:")&&(i.add(s.substring(12)),r.add("moduleRemoved"))}processRenameEntries(t,r,o,i,s){for(let a of t)s.push(a.info),o.add(a.info.newName),i.add(a.info.oldName),r.add(a.kind)}buildAddedNamesSet(t,r){let o=new Set;for(let i of t)i.startsWith("dep-added:")&&o.add(i.substring(10));for(let i of r)o.add(i.info.newName);return o}emitIncrementalReload(t,r,o,i,s){f.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...r].join(",")}], removed=[${[...o].join(",")}], added=[${[...i].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...r],removedModuleNames:[...o],addedModuleNames:[...i],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:r}=this.collectPendingState();if(t.length===0&&r.length===0)return;if(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 o=new Set,i=new Set,s=new Set,a=[];this.processTagsIntoSets(t,o,i,s),this.processRenameEntries(r,o,i,s,a);for(let l of i)s.delete(l);if(i.size===0&&s.size===0&&a.length===0){f.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,r);this.emitIncrementalReload(o,i,s,c,a)}normalizeSrcPath(t){return U(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let r=new Map(t.map(i=>[i.name,i])),o=new Map(t.map(i=>[this.normalizeSrcPath(i.srcPath),i]));return{byName:r,bySrcPath:o}}detectModuleRenames(t,r,o,i){for(let[s,a]of t){let c=r.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),o.add(a.name),i.add(c.name);let l=ut.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,o,i){for(let[s,a]of t){if(o.has(s))continue;let c=r.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),o.add(s),i.add(s),f.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,r,o){for(let[i]of t)o.has(i)||r.has(i)||(this.pendingTags.push(`dep-added:${i}`),o.add(i))}detectRemovedModules(t,r,o){for(let[i]of t)if(!o.has(i)&&!r.has(i)){this.pendingTags.push(`dep-removed:${i}`),o.add(i);let s=ut.join(this.depMapDir,i,L.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(o=>o.startsWith("dep-")),r=this.pendingRenames.map(o=>`${o.kind}(${o.info.oldName}\u2192${o.info.newName})`);f.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${r.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:r,bySrcPath:o}=this.buildModuleLookupMaps(this.lastModules),{byName:i,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(o,s,a,c),this.detectModuleMoves(r,i,a,c),this.detectAddedModules(i,r,c),this.detectRemovedModules(r,i,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let r=pn.readFileSync(t,"utf-8");return oI("sha256").update(r).digest("hex")}catch{return null}}};import{spawn as sI}from"child_process";var aI=["install","--all"];async function cI(n,e,t,r){return new Promise(o=>{let i=sI(n,e,{cwd:t,env:{...process.env,DEVECO_SDK_HOME:r},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";i.stdout?.on("data",c=>{s+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()}),i.on("close",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1292
1292
|
`);o({exitCode:c??-1,output:l})}),i.on("error",c=>{let l=[s,a].filter(Boolean).join(`
|
|
1293
1293
|
`);o({exitCode:-1,output:l+`
|
|
1294
1294
|
`+c.message})})})}function lI(n){n.split(/\r?\n/).filter(Boolean).forEach(e=>f.info("[ohpm] %s",e))}async function Km(n,e){try{let{exitCode:t,output:r}=await cI(e.nodePath,[e.ohpmJsPath,...aI],n,e.sdkPath);return lI(r),t===0?(f.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(f.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",t),f.error("ohpm \u8F93\u51FA: %s",r),!1)}catch(t){return f.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Xm={UNINITIALIZED:-32099,UNKNOWN:-32e3},Vo=class n extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new n(e,Xm.UNINITIALIZED)}static unknown(e="Unknown error"){return new n(e,Xm.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var Mr=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;try{this.startConfigWatcher(),this.startLspProxy(e)}catch(t){throw f.error(`[ArktsLspManager] start() synchronous failure: ${t instanceof Error?t.message:String(t)}`),t}}sendNotification(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){f.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}async diagnostic(e){if(!this.lspProxy)throw new Error("[ArktsLspManager] diagnostic before LSP ready");return this.lspProxy.diagnostic(e)}async sendFeatureRequest(e,t){if(!this.useStandardProtocol)throw new Error(`Language feature '${e}' is not supported on the installed DevEco Studio. The standard LSP protocol entry (plugins/openharmony/ace-server/out/standardIndex/index.js) was not found. Please upgrade DevEco Studio to version 26.0.0.610 or later to use this tool.`);if(!this.lspProxy)throw new Error("LSP not ready");return this.lspProxy.sendFeatureRequest(e,t)}get useStandardProtocol(){return this.config.useStandardProtocol}onAsyncOpenFile(e){this.lspProxy?.onAsyncOpenFile(e)}closeFileLegacy(e,t){this.lspProxy?.closeFileLegacy(e,t)}registerDiagnosticCallback(e){this.lspProxy?.registerDiagnosticCallback(e)}static async handleSyncProject(e,t,r){if(f.info("[ArktsLspManager] Received arkts/syncProject"),!e)return f.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),{status:"failed",reason:"workspaceRoot or sdkPath is empty"};let o=r?.skipHvigorSync===!0,i=await Fi(e,async()=>await Km(e,t)?o?(f.info("[ArktsLspManager] hvigor sync skipped (config up-to-date)"),{status:"success"}):await Zu(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 i.acquired?i.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 ia(this.config);t.setOnMessage(r=>this.handleLspMessage(r)),t.start(e,r=>this.handleLspInitialized(r)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)f.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:T,method:y.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();f.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let r=t?Vo.uninitialized(t):Vo.unknown();this.onMessage({jsonrpc:T,method:y.ARKTS_INITIALIZATION_FAILED,params:r.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(f.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:T,method:y.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new sa(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new aa(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(o=>({modulePath:o.modulePath??"",dependencies:o.dependencies??{},dynamicDependencies:o.dynamicDependencies??{}}));this.onMessage({jsonrpc:T,method:y.ARKTS_SYNC_COMPLETED,params:{success:!0,moduleSet:r}})}),this.depMapWatcher.start())}setOnConfigChanged(e){this.onConfigChanged=e}handleConfigChanged(e){f.info(`[ArktsLspManager] Config file changed: ${e.filePath}, notifying server`),this.onConfigChanged?.()}};var dI=10080*60*1e3,uI=7200*60*1e3,pI=120*1e3,_r=class n{manager=null;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;toolProvider;nodeMaxOldSpaceSize;onConfigChangedCallback=null;useStandardProtocol=!0;diagnosticWaiters=new Map;static FEATURE_METHOD_MAP={hover:y.HOVER,definition:y.DEFINITION,declaration:y.DECLARATION,references:y.REFERENCES,implementation:y.IMPLEMENTATION,completion:y.COMPLETION,signatureHelp:y.SIGNATURE_HELP,documentHighlight:y.DOCUMENT_HIGHLIGHT};constructor(e,t,r){this.projectPath=e,this.toolProvider=t,this.nodeMaxOldSpaceSize=r}setOnConfigChanged(e){this.onConfigChangedCallback=e}static getToolDefinition(){return{name:"check_ets_files",description:"\u5BF9\u4F20\u5165\u7684ets\u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5(ArkTS-Check)\u5E76\u5B9E\u65F6\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:_l.object({files:_l.array(_l.string()).describe('\u5F85\u68C0\u67E5\u7684 ETS \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.ets","file2.ets",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.initialized}async initialize(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initializing=!0,this.initPromise=this.doInitialize().then(()=>{this.initialized=!0}).finally(()=>{this.initializing=!1}),await this.initPromise}}async doInitialize(){let{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:o}=this.resolveProjectAndDeveco();this.useStandardProtocol=o;let i=pe(e),{logPath:s,indexPath:a}=this.getLogAndIndexPath(i);setImmediate(()=>{Ic(a,dI,"[ArkTS-Check]"),Ic(s,uI,"[ArkTS-Check]")}),zi(s);let c=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,l=Number.isNaN(c)?void 0:c;g.info(`ArktsCheck nodeMaxOldSpaceSize: incoming='${this.nodeMaxOldSpaceSize??"(unset)"}', parsed=${l??"undefined \u2192 dynamic formula applies"}`);let d=this.toolProvider.sdkPath;g.info(`ArktsCheck devecoStudioPath: ${t}, sdkPath: ${d}`),this.manager=new Mr({sdkPath:d,arktsLangServerPath:r,workspaceRoot:U(i),indexLogPath:a,nodeMaxOldSpaceSize:l,nodePath:this.toolProvider.nodePath,useStandardProtocol:o}),this.manager.setOnMessage(h=>this.handleLspMessage(h)),this.onConfigChangedCallback&&this.manager.setOnConfigChanged(this.onConfigChangedCallback),await new Promise((h,w)=>{this.initResolve=h,this.initReject=w,this.armInitTimer(ze),this.manager.start([]).catch(S=>{let A=S instanceof Error?S:new Error(String(S));this.failInit(A)})})}resolveProjectAndDeveco(){let e=Tt(this.projectPath);if(!e)throw new Error(`Failed to find HarmonyOS project from path: ${this.projectPath}`);this.projectPath=e;let t=this.toolProvider.devecoStudioPath??"";g.debug(`DevEco Studio installation path: ${t}`);let r=this.toolProvider.lspServerPath;if(!r)throw new Error("arkts-lang-server path not found");let o=le.resolve(le.dirname(r),"standardIndex","index.js"),i=Me.existsSync(o);return g.info(`ArktsCheck protocol: ${i?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${i})`),{harmonyRoot:e,devecoPath:t,arktsLangServerPath:r,useStandardProtocol:i}}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=Mn(e),o=await Me.promises.readFile(e,"utf8"),s=`deveco.apptool.${le.extname(e).replace(/^\./,"")||"plaintext"}`;return t.useStandardProtocol?this.checkFileStandard(t,r,o,s):this.checkFileLegacy(t,e,r,o,s)}async checkFileStandard(e,t,r,o){g.debug(`textDocument/didOpen uri=${t} content_len=${r.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:t,text:r,languageId:o,version:1}});try{g.debug(`textDocument/diagnostic uri=${t}`);let i=await e.diagnostic({textDocument:{uri:t}});return fI(i)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:t}})}}async checkFileLegacy(e,t,r,o,i){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"))},pI);this.diagnosticWaiters.set(s,{resolve:c,reject:l,timer:d})});g.debug(`textDocument/didOpen(legacy) uri=${r} content_len=${o.length}`),e.onAsyncOpenFile({textDocument:{uri:r,text:o,languageId:i,version:o.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=[],o=this.collectValidFiles(e.files,t);return o.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
@@ -1300,13 +1300,13 @@ ${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let r=this
|
|
|
1300
1300
|
`):"No valid C/C++ files"}],isError:!0};this.manager.patchSdkPathInCompileCommands();for(let c of o){await yI(hI);try{let l=await this.checkFile(c);r.push(gI(c,l))}catch(l){t.push(`${c} => wait for diagnostics failed: ${l.message}`)}}let i=t.length>0,s=[];t.length>0&&s.push(t.join(`
|
|
1301
1301
|
`)),r.length>0&&s.push(r.join(`
|
|
1302
1302
|
`));let a=s.join(`
|
|
1303
|
-
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Mn(e),r=await fn.promises.readFile(e,"utf8"),o=Wi(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,o=[];for(let i of e){let s=Hr.resolve(Hr.isAbsolute(i)?i:Hr.join(r,i));if(!fn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!fn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!On(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(fn.realpathSync(s))}catch{o.push(s)}}return o}};function gI(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 yI(n){return new Promise(e=>setTimeout(e,n))}import*as Ur from"fs";import*as la from"path";var $r=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 Fr();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 o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return ca(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Fr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return ca("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Fr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return ca("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}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}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=Mn(e),o=await Ur.promises.readFile(e,"utf8"),i=Wi(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=la.isAbsolute(e)?e:la.join(this.manager.projectRoot,e);return!Ur.existsSync(t)||!Ur.statSync(t).isFile()||!On(t)?null:t}};import{spawn as wI}from"child_process";import*as ua from"fs";import*as Zm from"path";var vI=30*1e3,SI=30*1e3,da=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new ln;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new cn(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,ze),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,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},SI);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}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=wI(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=cr(this.config.workspaceRoot),t=st(e),r=Zm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.3.0-TD.2.4"},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=vI){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, 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 o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:T,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:T,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ua.existsSync(this.config.logPath)||ua.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)),st(r)}}catch{}return e}};import*as zo from"path";import*as Wt from"fs";var Jo=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.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b())return;let e=sr(this.projectRoot);if(!Wt.existsSync(e))return;let t=Wt.readFileSync(e,"utf8");if(!t.includes(Ji))return;let r=t.replaceAll(Ji,this.config.toolProvider.sdkPath);Wt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Ji} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Fn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Fi(e,async()=>{try{return await tp(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.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(ze);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Tt(this.config.workspaceRoot);this.resolvedRoot=e?pe(e):pe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();zi(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=zo.dirname(sr(this.resolvedRoot));try{Wt.mkdirSync(o,{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: ${o}`);let i=new da({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.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 o=this.initReject;this.clearInitHandlers(),o?.(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 o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}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=zo.join(nn(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=zo.join(e,"lsp-log",t);return Wt.mkdirSync(r,{recursive:!0}),pe(r)}catch{return"auto"}}};function Qm(n){let e=Hi(n);return f.info(`[SyncGuard] ${e.reason}`),e}var $l=(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))($l||{}),th=(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))(th||{}),bt=3,jl=600*1e3,Hl=100,pa=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,_n(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=Tt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new bI({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Ol(),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:de.object({target:de.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:de.object({files:de.array(de.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){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));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:de.object({query:de.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:de.object({file:de.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:de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.number().describe("Character offset in the line (0-based)"),direction:de.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=mn.join(mn.dirname(e),"standardIndex","index.js"),r=eh.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=R.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1303
|
+
`).trim();return!i&&r.length===0&&(a="No diagnostic information collected"),{content:[{type:"text",text:a}],isError:i}}async checkFile(e){let t=Mn(e),r=await fn.promises.readFile(e,"utf8"),o=Wi(e),i=this.manager.registerDiagnosticCallback(t);this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:t,text:r,languageId:o,version:r.length}}});try{return await i}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:t}}})}}collectValidFiles(e,t){let r=this.manager.projectRoot,o=[];for(let i of e){let s=Hr.resolve(Hr.isAbsolute(i)?i:Hr.join(r,i));if(!fn.existsSync(s)){t.push(`File does not exist: ${i}`);continue}if(!fn.statSync(s).isFile()){t.push(`Not a regular file: ${i}`);continue}if(!On(s)){t.push(`Not a supported C/C++ file: ${i}`);continue}try{o.push(fn.realpathSync(s))}catch{o.push(s)}}return o}};function gI(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 yI(n){return new Promise(e=>setTimeout(e,n))}import*as Ur from"fs";import*as la from"path";var $r=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 Fr();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 o=n.FEATURE_METHOD_MAP[e];if(!o)return{content:[{type:"text",text:`Unknown feature: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleLspFeature: ${e} file=${r} line=${t.line} char=${t.character}`);try{let i=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(o,c)});return{content:[{type:"text",text:i==null?`${e}: no result`:`${e}: ${JSON.stringify(i,null,2)}`}]}}catch(i){return ca(e,i)}}async handleWorkspaceSymbolRaw(e){if(!this.manager.ready)return null;try{let t=await this.manager.sendFeatureRequest(y.WORKSPACE_SYMBOL,{query:e});return Array.isArray(t)?t:t==null?null:[t]}catch(t){return g.error(`[ClangdLspTool] handleWorkspaceSymbolRaw failed: ${t.message}`),null}}async handleDocumentSymbol(e){if(!this.manager.ready)return Fr();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e}`}],isError:!0};g.info(`[ClangdLspTool] handleDocumentSymbol: file=${t}`);try{let r=await this.withOpenFile(t,async i=>this.manager.sendFeatureRequest(y.DOCUMENT_SYMBOL,{textDocument:{uri:i}}));return{content:[{type:"text",text:r==null?"documentSymbol: no result":`documentSymbol: ${JSON.stringify(r,null,2)}`}]}}catch(r){return ca("documentSymbol",r)}}async handleCallHierarchy(e){if(!this.manager.ready)return Fr();if(e.direction==="outgoing")return{content:[{type:"text",text:"callHierarchy outgoing is not supported by clangd (incoming only)"}],isError:!0};let t=this.resolveSingleFile(e.file);if(!t)return{content:[{type:"text",text:`File does not exist or is not a C/C++ file: ${e.file}`}],isError:!0};g.info(`[ClangdLspTool] handleCallHierarchy: file=${t} line=${e.line} char=${e.character} direction=${e.direction}`);try{let r=await this.withOpenFile(t,i=>this.fetchCallHierarchyResult(i,e));return{content:[{type:"text",text:`callHierarchy (${e.direction}): ${JSON.stringify(r,null,2)}`}]}}catch(r){return ca("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}}),o=this.normalizeCallHierarchyItems(r);if(o.length===0)return{items:[],calls:[]};let i=await this.collectIncomingCalls(o);return{items:o,calls:i}}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=Mn(e),o=await Ur.promises.readFile(e,"utf8"),i=Wi(e);g.info(`[ClangdLspTool] withOpenFile didOpen uri=${r} langId=${i} len=${o.length}`),this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didOpen",params:{textDocument:{uri:r,text:o,languageId:i,version:o.length}}});try{return await t(r)}finally{this.manager.sendNotification({jsonrpc:"2.0",method:"textDocument/didClose",params:{textDocument:{uri:r}}})}}resolveSingleFile(e){let t=la.isAbsolute(e)?e:la.join(this.manager.projectRoot,e);return!Ur.existsSync(t)||!Ur.statSync(t).isFile()||!On(t)?null:t}};import{spawn as wI}from"child_process";import*as ua from"fs";import*as Zm from"path";var vI=30*1e3,SI=30*1e3,da=class{config;client=null;clangdProcess=null;nextRequestId=1;requestCallbacks=new ln;diagnosticWaiters=new Map;lastStartErrorMessage=null;onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}async start(e){let t=!1;try{f.info(`[ClangdLspProxy] clangdPath: ${this.config.clangdPath}`),f.info(`[ClangdLspProxy] workspaceRoot: ${this.config.workspaceRoot}`),f.info(`[ClangdLspProxy] compileCommandsDir: ${this.config.compileCommandsDir}`),this.ensureLogDir(),this.clangdProcess=this.spawnClangd();let r={serverPath:"",logPath:this.config.logPath,indexingDataLocation:this.config.logPath,cwd:this.config.workspaceRoot,nodePath:this.config.nodePath};this.client=new cn(r),this.client.on("message",i=>this.handleRawMessage(i)),this.client.on("error",i=>this.handleError(i)),this.client.attachProcess(this.clangdProcess,{stderrAsError:!1});let o=this.buildInitializeParams();await this.sendLspRequest(y.INITIALIZE,o,ze),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,o)=>{let i=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&o(new Error(`Wait for clangd diagnostics timeout, uri: ${t}`))},SI);this.diagnosticWaiters.set(t,{resolve:r,reject:o,timer:i})})}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=wI(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=cr(this.config.workspaceRoot),t=st(e),r=Zm.basename(e)||"workspace";return{processId:process.pid,clientInfo:{name:"devecocli-mcp-server",version:"0.3.0"},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=vI){if(!this.client)return Promise.reject(new Error("[ClangdLspProxy] client not ready"));let o=this.nextRequestId++,i=this.requestCallbacks.registerPending(o,e,r);return this.client.sendRequest(e,t,o),i}handleRawMessage(e){let t;try{t=JSON.parse(e)}catch(r){let o=r instanceof Error?r.message:String(r);f.error(`[ClangdLspProxy] JSON parse error: ${o}, 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 o=e.error;f.warn(`[ClangdLspProxy] LSP error id=${r}: code=${o.code??-1} message=${o.message??"unknown"}`),this.requestCallbacks.rejectPending(r,new Error(`LSP error ${o.code??-1}: ${o.message??"unknown"}`))}else this.requestCallbacks.resolvePending(r,e.result)}handleNotification(e){let t=e.method;if(t)switch(t){case y.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(e.params);break;case y.PROGRESS:this.onMessage({jsonrpc:T,method:y.PROGRESS,params:e.params});break;case y.WINDOW_SHOW_MESSAGE:f.info(`[ClangdLspProxy] window/showMessage: ${JSON.stringify(e.params)}`);break;case y.WINDOW_LOG_MESSAGE:f.info(`[ClangdLspProxy] window/logMessage: ${JSON.stringify(e.params)}`);break;default:this.onMessage({jsonrpc:T,method:t,params:e.params})}}handlePublishDiagnostics(e){if(!e||!e.uri)return;let t=this.normalizeClangdUri(e.uri),r=this.diagnosticWaiters.get(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.diagnosticWaiters.get(s),r&&this.diagnosticWaiters.delete(s)}else r&&this.diagnosticWaiters.delete(t);if(!r)return;clearTimeout(r.timer);let o=Array.isArray(e.diagnostics)?e.diagnostics:[],i=o.length;f.info(`[ClangdLspProxy] diagnostics received uri=${t} count=${i}`),r.resolve(o)}handleError(e){for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear(),this.requestCallbacks.rejectAll(e),this.onMessage({jsonrpc:T,method:y.CPP_ERROR,params:{message:e.message}})}ensureLogDir(){if(this.config.logPath)try{ua.existsSync(this.config.logPath)||ua.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)),st(r)}}catch{}return e}};import*as zo from"path";import*as Wt from"fs";var Jo=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.patchSdkPathInCompileCommands(),this.proxy.sendFeatureRequest(e,t)}registerDiagnosticCallback(e){return this.proxy?this.proxy.registerDiagnosticCallback(e):Promise.reject(new Error("[ClangdLspManager] LSP not ready"))}patchSdkPathInCompileCommands(){if(!b())return;let e=sr(this.projectRoot);if(!Wt.existsSync(e))return;let t=Wt.readFileSync(e,"utf8");if(!t.includes(Ji))return;let r=t.replaceAll(Ji,this.config.toolProvider.sdkPath);Wt.writeFileSync(e,r,"utf8"),f.info(`[CppCheck] Patched SDK path in compile_commands.json: ${Ji} -> ${this.config.toolProvider.sdkPath}`)}static async handleSyncCppProject(e,t){if(f.info("[ClangdLspManager] Received cpp/syncProject"),!e)return f.error("[ClangdLspManager] handleSyncCppProject: workspaceRoot or devecoPath is empty"),{status:"failed",reason:"workspaceRoot or devecoPath is empty"};if(Fn(e).length===0)return f.info("[ClangdLspManager] No C++ modules found, skipping compileNative"),{status:"success"};let o=await Fi(e,async()=>{try{return await tp(e,t),f.info("[ClangdLspManager] compileNative + merge compile_commands completed"),{status:"success"}}catch(i){let s=i instanceof Error?i.message:String(i);return f.error(`[ClangdLspManager] compileNative failed: ${s}`),{status:"failed",reason:s}}});return o.acquired?o.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(ze);try{this.startProxy()}catch(r){this.failInit(r instanceof Error?r:new Error(String(r)))}})}startProxy(){let e=Tt(this.config.workspaceRoot);this.resolvedRoot=e?pe(e):pe(this.config.workspaceRoot);let t=this.config.logPath??this.getLogPath();zi(t);let r=this.config.toolProvider.clangdPath;if(!r){let s="clangd executable not found inside DevEco Studio SDK";f.error(`[ClangdLspManager] ${s}`),this.failInit(new Error(s));return}let o=zo.dirname(sr(this.resolvedRoot));try{Wt.mkdirSync(o,{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: ${o}`);let i=new da({clangdPath:r,workspaceRoot:this.resolvedRoot,compileCommandsDir:o,logPath:t,nodePath:this.config.toolProvider.nodePath});i.setOnMessage(s=>this.handleLspMessage(s)),this.proxy=i,i.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 o=this.initReject;this.clearInitHandlers(),o?.(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 o=t.params;switch(r){case y.DID_OPEN:this.proxy.sendDidOpen(o);break;case y.DID_CHANGE:this.proxy.sendDidChange(o);break;case y.DID_CLOSE:this.proxy.sendDidClose(o);break;default:this.proxy.sendNotification(r,o)}}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=zo.join(nn(),"CppCheck"),t=`${Date.now()}${process.hrtime.bigint()%1000000n}`,r=zo.join(e,"lsp-log",t);return Wt.mkdirSync(r,{recursive:!0}),pe(r)}catch{return"auto"}}};function Qm(n){let e=Hi(n);return f.info(`[SyncGuard] ${e.reason}`),e}var $l=(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))($l||{}),th=(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))(th||{}),bt=3,jl=600*1e3,Hl=100,pa=class{server;toolRouter;config;arktsCheckTool=null;cppCheckTool=null;cppLspTool=null;cppLspManager=null;projectState=0;workspaceRoot="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";configChangedTriggeredResync=!1;syncSkippedDueToLock=!1;syncSkipStartedAt=0;standardProtocolAvailable=!1;cppProjectState=0;cppInitPromise=null;cppNeedsReinit=!1;cppInitRetryCount=0;cppSyncSkippedDueToLock=!1;cppSyncSkipStartedAt=0;cppHasNoCppCode=!1;constructor(e){this.config=e,_n(e.debug??!1);let t,r=e.projectPath?.trim()??"";this.originalProjectPath=r,r==="."?(t=process.cwd(),g.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):r===""?(t="",g.info("Constructor: configuredPath is empty, startPath remains empty")):(t=r,g.info(`Constructor: using configured path as startPath: '${t}'`));let o=Tt(t);g.info(`Constructor: findHarmonyProject('${t}') => ${o??"null"}`),this.config.projectPath=o??void 0,this.server=new bI({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Ol(),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:de.object({target:de.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:de.object({files:de.array(de.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){g.info("Skip registering LSP feature tools (hover/definition/declaration/references/implementation, workspaceSymbol, documentSymbol, callHierarchy): standard LSP protocol unavailable (standardIndex/index.js not found). These tools require a DevEco Studio version that ships the standard LSP server entry.");return}let e=de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.number().describe("Character offset in the line (0-based)")});for(let{name:t,description:r,feature:o}of this.getPositionFeatures())this.toolRouter.add({name:t,description:r,inputSchema:e},async i=>this.handleLspFeatureCall(o,i));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:de.object({query:de.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:de.object({file:de.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:de.object({file:de.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:de.number().describe("Line number (0-based)"),character:de.number().describe("Character offset in the line (0-based)"),direction:de.enum(["incoming","outgoing"]).describe('"incoming" = who calls this function, "outgoing" = what this function calls')})},async e=>this.handleCallHierarchyCall(e))}detectStandardProtocolAvailable(){try{let e=this.config.toolProvider.lspServerPath;if(!e)return g.info("Standard LSP protocol unavailable: arkts-lang-server path not found"),!1;let t=mn.join(mn.dirname(e),"standardIndex","index.js"),r=eh.existsSync(t);return g.info(`ArktsCheck protocol: ${r?"standard LSP":"legacy ace-server"} (standardIndex/index.js exists=${r})`),r}catch(e){return g.warn(`Failed to detect standard LSP protocol availability: ${e}`),!1}}validateContainment(e){let t=this.config.projectPath;if(t){let o=[];for(let i of e){let s=R.isPathContainedWithSymlink(i,t);s.contained||(g.warn(`Containment check failed: ${s.reason}`),o.push(s.reason))}return o.length>0?{content:[{type:"text",text:o.join(`
|
|
1304
1304
|
`)}],isError:!0}:null}let r=e.filter(o=>mn.isAbsolute(o));return r.length>0?(g.warn(`Absolute paths rejected (no project root): ${r.join(", ")}`),{content:[{type:"text",text:r.map(o=>`Absolute path is not allowed: ${o}`).join(`
|
|
1305
1305
|
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(d=>typeof d=="string"):[];if(t.length===0)return g.warn("check tool called with empty files list"),{content:[{type:"text",text:"No files provided"}],isError:!0};if(t.length>Hl)return g.warn(`check tool called with ${t.length} files (max: ${Hl})`),{content:[{type:"text",text:`Too many files: ${t.length}. Maximum allowed is ${Hl}.`}],isError:!0};let{etsFiles:r,cppFiles:o,unsupported:i}=PI(t);i.length>0&&g.warn(`Unsupported file types in check request: ${i.join(", ")}`);let s=i.map(d=>`Unsupported file type: ${d} (only .ets and C/C++ source/header files are supported)`),a=[];r.length>0&&this.mergeCheckResult(await this.callArktsCheck(r),s,a),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),s,a);let c=s.length>0;return{content:[{type:"text",text:[a.join(`
|
|
1306
1306
|
`),s.join(`
|
|
1307
1307
|
`)].filter(d=>d.trim().length>0).join(`
|
|
1308
1308
|
`).trim()||"No diagnostics collected"}],isError:c}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS check rejected: project is ${$l[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e});default:return g.error(`ArkTS check: unknown project state ${this.projectState}, files: ${e.join(", ")}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleLspFeatureCall(e,t){let r=t.file,o=t.line,i=t.character;return typeof r!="string"||typeof o!="number"||typeof i!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:this.routeLspRequest(r,e,async()=>{if(r.endsWith(".ets"))return this.arktsCheckTool.handleLspFeature(e,{file:r,line:o,character:i});let s=e;return this.cppLspTool.handleLspFeature(s,{file:r,line:o,character:i})})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.routeWorkspaceSymbolRequest(t)}async routeWorkspaceSymbolRequest(e){let t=this.projectState===4&&this.arktsCheckTool!==null,r=this.cppProjectState===4&&!this.cppHasNoCppCode&&this.cppLspTool!==null;if(!t&&!r){let a=this.describeArktsState(),c=this.describeCppState();return g.info(`workspaceSymbol rejected: ArkTS ${a}; C++ ${c}`),{content:[{type:"text",text:`workspaceSymbol: ArkTS ${a}; C++ ${c}`}],isError:!0}}let o=[],i=new Set;if(t)try{this.mergeSymbolItems(await this.arktsCheckTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){g.warn(`workspaceSymbol ArkTS query failed: ${a.message}`)}if(r)try{this.mergeSymbolItems(await this.cppLspTool.handleWorkspaceSymbolRaw(e),i,o)}catch(a){g.warn(`workspaceSymbol C++ query failed: ${a.message}`)}return{content:[{type:"text",text:o.length===0?"workspaceSymbol: no result":`workspaceSymbol: ${JSON.stringify(o,null,2)}`}]}}symbolDedupKey(e){let t=e,r=t?.location?.uri??"",o=t?.location?.range?.start?.line??0,i=t?.location?.range?.start?.character??0;return`${r}:${o}:${i}`}mergeSymbolItems(e,t,r){if(e)for(let o of e){let i=this.symbolDedupKey(o);t.has(i)||(t.add(i),r.push(o))}}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}/${bt})`;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}/${bt})`;case 4:return this.cppHasNoCppCode?"ready (no C++ code)":"ready";default:return"unknown"}}async handleDocumentSymbolCall(e){let t=e.file;return typeof t!="string"?{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0}: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,o=e.character,i=e.direction;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}:i!=="incoming"&&i!=="outgoing"?{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0}:this.routeLspRequest(t,`callHierarchy(${i})`,async()=>t.endsWith(".ets")?this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}):this.cppLspTool.handleCallHierarchy({file:t,line:r,character:o,direction:i}))}async handleCodeActionCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e);return t?this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:o})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}async handleRenameCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.newName;return!t||typeof i!="string"||i.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0}:this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:o,newName:i}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:o}=this.extractPositionArgs(e),i=e.direction;return t?i!=="supertypes"&&i!=="subtypes"?{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0}:this.routeArktsRequest(`typeHierarchy(${i})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:o,direction:i})):{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0}}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,o=e.character;return typeof t!="string"||typeof r!="number"||typeof o!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:o}}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return g.warn(`ArkTS ${e} rejected: project is ${$l[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return g.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t();default:return g.error(`ArkTS ${e}: unknown project state ${this.projectState}`),{content:[{type:"text",text:`Unknown project state: ${this.projectState}`}],isError:!0}}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),g.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(g.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(g.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=bt?(g.error(`Init retry limit reached (${this.initRetryCount}/${bt}), will not auto-retry`),{content:[{type:"text",text:`Project initialization failed repeatedly (auto-retry exhausted: ${this.initRetryCount}/${bt}). 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}):(g.info(`Error check: auto-retrying (${this.initRetryCount}/${bt})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async routeCppRequest(e,t){switch(this.cppProjectState){case 0:return this.handleCppIdleCheck();case 1:case 2:return g.warn(`C++ ${e} rejected: C++ project is ${th[this.cppProjectState]}`),{content:[{type:"text",text:"C++ project is syncing (compileNative), please retry in 25 seconds"}],isError:!0};case 3:return g.warn(`C++ ${e} rejected: clangd is initializing`),{content:[{type:"text",text:"C++ LSP (clangd) is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleCppErrorCheck();case 4:return this.cppHasNoCppCode?{content:[{type:"text",text:"No C++ code in this project"}],isError:!0}:this.cppLspManager?.ready?t():{content:[{type:"text",text:"C++ LSP is not ready, please retry later"}],isError:!0};default:return g.error(`C++ ${e}: unknown C++ project state ${this.cppProjectState}`),{content:[{type:"text",text:`Unknown C++ project state: ${this.cppProjectState}`}],isError:!0}}}async routeLspRequest(e,t,r){return e.endsWith(".ets")?this.routeArktsRequest(t,r):On(e)?this.routeCppRequest(t,r):{content:[{type:"text",text:`Unsupported file type: ${e} (only .ets and C/C++ source/header files are supported)`}],isError:!0}}async handleCppIdleCheck(){if(this.ensureCppProjectReady(),this.config.projectPath){let e;return this.cppSyncSkippedDueToLock?(e=`Another build process is running, C++ sync deferred (waiting ${this.cppSyncSkipStartedAt>0?Math.round((Date.now()-this.cppSyncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,this.cppSyncSkippedDueToLock=!1):e="C++ project detected, syncing (compileNative), please retry in 25 seconds",g.info(`C++ idle check: project '${this.config.projectPath}', triggering C++ init`),{content:[{type:"text",text:e}],isError:!0}}return{content:[{type:"text",text:"No HarmonyOS project detected for C++ tools."}],isError:!0}}async handleCppErrorCheck(){return this.cppInitRetryCount>=bt?(g.error(`C++ init retry limit reached (${this.cppInitRetryCount}/${bt}), will not auto-retry`),{content:[{type:"text",text:`C++ project initialization failed repeatedly (auto-retry exhausted: ${this.cppInitRetryCount}/${bt}). 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}):(g.info(`C++ error check: auto-retrying (${this.cppInitRetryCount}/${bt})`),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 o=e.content.map(i=>i.text).filter(i=>i&&i.trim().length>0).join(`
|
|
1309
|
-
`);o&&(e.isError?t.push(o):r.push(o))}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){g.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=>g.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,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.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,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new EI;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Bu();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Tt(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Tt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Tt(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new _r(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Qm(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await Mr.handleSyncProject(e,this.config.toolProvider,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=jl?(g.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${jl/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=Fn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new Jo({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new jr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new $r(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await Jo.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(r/1e3);return r>=jl?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Uu(),$u()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function PI(n){let e=[],t=[],r=[];for(let o of n)mn.extname(o).toLowerCase()===".ets"?e.push(o):On(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Ul(n){return new pa(n)}import*as Bl from"fs";import*as hn from"path";import{spawn as CI}from"child_process";async function nh(n){_n(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await II(n),i=RI(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),kI(i)}async function II(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=pe(hn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=Bi(process.cwd());e=pe(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=pe(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=hn.resolve(hn.dirname(r),"standardIndex","index.js"),i=hn.join(nn(),"lsp-server",String(Date.now()));Bl.mkdirSync(i,{recursive:!0});let s=AI(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${o}, logPath=${i}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:o,logPath:i,serverMaxSize:s}}function AI(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,o=Number.isFinite(r)&&r>0?r:void 0,i=DI(n,e),s=Yi(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function DI(n,e){try{let t=[];return new Jn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new kt(n).getAllModuleInfo().length}catch{return 0}}function RI(n,e,t,r,o){let i=hn.join(e,"lspLog");Bl.mkdirSync(i,{recursive:!0});let s=TI(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),CI(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function TI(n,e,t,r,o){let i=U(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,n,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${U(t)}`,`--sdkPath=${U(r)}`]}function kI(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as rh from"fs";import*as Yn from"path";import{spawn as xI}from"child_process";async function oh(n){_n(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await NI(n),o=Yn.join(t,"compile_commands.json");rh.existsSync(o)||g.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=LI(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),MI(i)}async function NI(n){let e;if(n.projectPath)e=pe(Yn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=Bi(process.cwd());e=pe(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=pe(Yn.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=sr(e),o=Yn.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function LI(n,e,t){let r=OI(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),xI(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function OI(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function MI(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function FI(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await I.new();b()||r.require({clt:!1});let i=Ul({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await i.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await i.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Wl=new _I("serve").description("Host bundled auxiliary protocol servers");Wl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await FI()});Wl.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));let e=await I.new();n.arkts?await nh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await oh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var ih=Wl;import{Command as HR,InvalidArgumentError as Ld}from"commander";import{red as $a,dim as $R}from"colorette";import*as re from"fs";import*as Et from"path";import PR from"adm-zip";import CR from"proper-lockfile";import fy from"ora";import*as pt from"fs";import*as oi from"path";var gn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Kn={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Br="1.9.1",GV=48*1024*1024,sh=280,ah=6,ch=100,lh=3,dh=28,Gl=10,uh=/API参考|APIReference/i,Yo=200,ph=12,fh=4,ql=8,mh=6,fa=700,Vl=250,zl=400,hh=1320,gh=120,yh=450,wh=250,vh=500,Sh=480,bh=80,Eh=200,Ph=60,Ch=200,Ih=40,Ah=200,Dh=200,Rh=40,Wr=500,Th=Object.fromEntries(gn.map((n,e)=>[Kn[n],e])),yn=Object.fromEntries(gn.map((n,e)=>[n,e]));import*as Ko from"fs";import*as O from"path";import{fileURLToPath as Lh}from"url";import*as wn from"fs";import*as kh from"path";import{homedir as jI}from"os";var HI="deveco-cli",Jl,Xn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function $I(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Ni(n)!==""}function xh(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Ni(n))||kh.join(jI(),".local","share",HI);try{return Li(t)}catch(r){throw new Xn(r instanceof Error?r.message:String(r))}}async function Nh(){let n=xh();await wn.promises.mkdir(n,{recursive:!0});let e;try{e=await wn.promises.realpath(n)}catch(r){throw new Xn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await wn.promises.stat(e)).isDirectory())throw new Xn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Jl=e,e}function ma(n){let e=Gr();return $I()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Gr(){if(Jl!==void 0)return Jl;let n=xh();try{if(wn.existsSync(n))return wn.realpathSync(n)}catch{}return n}var UI="docs";function qr(){return O.join(Gr(),UI)}function Q(){return O.join(qr(),".index")}function ha(){return O.join(Q(),"build.lock")}function Xo(){return O.join(Q(),"build-status.json")}function Vr(){return O.join(Q(),"build-meta.json")}function Zn(){return O.join(Q(),"search.db")}function Zo(){return O.join(Q(),"sqlite-backend.json")}function Qo(){return O.join(Q(),"jieba-backend.json")}function Gt(){return O.join(Q(),".tmp")}function BI(){return O.join(Gr(),"logs")}function zr(){return O.join(BI(),"doc-init.log")}function WI(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function Oh(n,e){return O.dirname(WI(n,e))}function Mh(){let n=Lh(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?Oh(n,e):O.join(e,"..","..","..")}function GI(...n){let e=Lh(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(Oh(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function _h(...n){let e=Mh(),t=Ko.realpathSync(e);for(let r of GI(...n))try{let o=Ko.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=Ko.realpathSync(r);if(!co(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function vn(){return _h("docs.zip")}function Yl(){return _h("index.zip")}function Fh(){return O.join(Mh(),"index","data")}import*as qt from"fs";import*as Qn from"path";var Vt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ga=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function jh(n){return n instanceof ga}var Kl=null;function Xl(n){Kl=n}function Zl(){if(Kl)return Kl;let n=Q();if(Vt.every(o=>qt.existsSync(Qn.join(n,o))))return n;let t=Fh();if(Vt.every(o=>qt.existsSync(Qn.join(t,o))))return t;throw new ga("Lexicon files not found. Install the documentation index first (index.zip).")}function Hh(){Zl()}function er(n){let e=Qn.join(Zl(),n);return qt.readFileSync(e,"utf-8")}function $h(n,e){return qt.readFileSync(Qn.join(e,n),"utf-8")}async function Uh(n,e=Zl()){await qt.promises.mkdir(n,{recursive:!0});for(let t of Vt){let r=Qn.join(e,t),o=Qn.join(n,t);await qt.promises.copyFile(r,o)}}import*as ya from"fs";import*as Bh from"path";import*as Wh from"yauzl";var ei=null;function qI(n){return new Promise((e,t)=>{Wh.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function VI(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function zI(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=VI(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function JI(){ei?.zipfile.close(),ei=null}async function YI(n){let e=Bh.resolve(n),t=await ya.promises.stat(e),r=ei;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;JI();let o=await qI(e),i=await zI(o);return ei={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},ei}function KI(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function XI(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await KI(n.zipfile,e)}finally{r()}}function ZI(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 QI(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Gh(n){let e=vn();if(!e)throw new Error("docs.zip not found");let t=await YI(e),r=QI(t.entries,ZI(n));if(!r)throw new Error(`Document not found: ${n}`);return(await XI(t,r)).toString("utf-8")}function Ql(){let n=vn();return n!==null&&ya.existsSync(n)}import*as he from"fs";import*as zt from"path";import qh from"adm-zip";import*as ti from"fs";import*as va from"path";var wa=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function ni(n){return n instanceof Xn||n instanceof wa||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function nd(n){return new wa(n)}function eA(){return yt(Gr())}function td(n,e,t){let r=xi(n,e);if(r===null)throw nd(`${t} resolves outside the data directory.`);return r}async function ed(n,e){await ti.promises.mkdir(n,{recursive:!0});let t=td(n,e,"directory");if(!(await ti.promises.stat(t)).isDirectory())throw nd("path must be a directory.")}function ri(n){let e=eA();try{let t=td(n,e,"file");if(!ti.statSync(t).isFile())throw nd("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){td(va.dirname(n),e,"file parent");return}throw t}}async function Jr(n={}){let e=n.mode??"write",t=await Nh();await ed(qr(),t),await ed(Q(),t),e==="write"&&await ed(Gt(),t);for(let r of[Zn(),Vr(),Xo(),ha(),Qo(),Zo(),...Vt.map(o=>va.join(Q(),o))])ri(r)}var rd=["search.db","build-meta.json",...Vt],tA=["corpus.json","corpus-offsets.json","orama.dpack"];async function nA(n){for(let e of tA)await he.promises.rm(zt.join(n,e),{force:!0})}async function rA(n){let e=await he.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await he.promises.rm(zt.join(n,t.name),{recursive:!0,force:!0})}function Vh(n){let t=new qh(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 oA(n){let e=Q();await he.promises.mkdir(e,{recursive:!0});for(let t of rd){let r=zt.join(e,t);await he.promises.rm(r,{force:!0}),await he.promises.rename(zt.join(n,t),r)}await nA(e),await he.promises.rm(Gt(),{recursive:!0,force:!0})}function zh(n){let e=Yl();if(!e)return!1;try{let t=Vh(e);return t.indexVersion===Br&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Jh(n){await Jr({mode:"write"});let e=Yl();if(!e)throw new Error("index.zip not found");let t=Vh(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=Gt();await he.promises.rm(r,{recursive:!0,force:!0}),await he.promises.mkdir(r,{recursive:!0});let o=new qh(e);for(let s of rd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await he.promises.writeFile(zt.join(r,s),a.getData())}let i=JSON.parse(await he.promises.readFile(zt.join(r,"build-meta.json"),"utf-8"));if(!he.existsSync(zt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await oA(r),await he.promises.mkdir(qr(),{recursive:!0}),await rA(qr()),i}async function Yh(){await he.promises.rm(Gt(),{recursive:!0,force:!0});let n=Q();for(let e of rd)await he.promises.rm(zt.join(n,e),{force:!0})}import{createHash as Kh}from"crypto";import*as Xh from"fs";async function Sa(n){return new Promise((e,t)=>{let r=Kh("sha256"),o=Xh.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function Zh(n){return Kh("sha256").update(n,"utf8").digest("hex")}var od=null;function iA(){let n=er("harmonyos-synonyms.json");return JSON.parse(n)}function sA(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function aA(){let n=sA(iA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function cA(){return od||(od=aA()),od}function id(n,e){let t=cA(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function Qh(n,e){let t=e?$h(n,e):er(n);return Zh(t)}function ba(n){return Qh("harmonyos-synonyms.json",n)}function Ea(n){return Qh("harmonyos-terms.txt",n)}var lA={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Pa(){try{let n=await pt.promises.readFile(Xo(),"utf-8");return JSON.parse(n)}catch{return{...lA}}}async function sd(n){let e=Xo();await pt.promises.mkdir(oi.dirname(e),{recursive:!0}),await pt.promises.writeFile(e,JSON.stringify(n,null,2))}function eg(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Sn(n){let t={...await Pa(),...n,updatedAt:Date.now()};return await sd(t),t}async function ad(){let n=vn();return n?Sa(n):null}async function cd(){try{let n=await pt.promises.readFile(Vr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Ca(n=!1){if(n)return"no-index";let e=await cd();if(!e||e.segmentCount===0)return"no-index";let t=await ad();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Br?"engine-upgraded":e.termsHash!==Ea()?"terms-changed":e.synonymsHash!==ba()?"synonyms-changed":null}function ii(){if(!Ql()||!pt.existsSync(Zn())||!pt.existsSync(Vr()))return!1;let n=oi.dirname(Zn());if(!Vt.every(e=>pt.existsSync(oi.join(n,e))))return!1;try{let e=pt.readFileSync(Vr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function ld(n=!1){return n?!0:Ql()?ii()?await Ca()!==null:!0:!1}async function tg(){let n=await Pa();return["installing","indexing","persisting"].includes(n.state)}import*as Ee from"fs";import*as sy from"os";import*as _e from"path";var ng=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),dd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),rg=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"]),og=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 dA=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,uA=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,pA=/[A-Z][a-zA-Z0-9]{2,}/g,fA=/@[A-Z][a-zA-Z0-9]*/g,mA=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ig=6,hA=/^[a-z][a-z0-9]{2,}$/,gA=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,yA=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,wA=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,vA=/^[A-Z][a-zA-Z0-9]+$/;function SA(n){return`"${n.replace(/"/g,'""')}"`}function ai(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(SA).join(` ${e} `)}function si(n){return ai(n,"OR")}function sg(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?si([...t,...r]):`(${si(t)}) AND (${si(r)})`}function ci(n){return yA.test(n)}function ag(n){return wA.test(n)&&n.length>=ig}function bA(n){return vA.test(n)}function li(n){return ci(n)||ag(n)||bA(n)}function EA(n){let e=n.trim().toLowerCase();return og.has(e)?!1:ng.has(e)}function PA(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ia(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function ud(n){return[...n.matchAll(dA)].map(e=>e[0])}function pd(n,e=ig){let t=[];for(let r of n.matchAll(uA))r[0].length>=e&&t.push(r[0]);return t}function Yr(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function ft(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function CA(n){let e=new Set;ft(e,n);let t=Ia(n);return t&&ft(e,t),Yr([...e])}function Aa(n){if(ci(n))return CA(n);let e=new Set;return ft(e,n),Yr([...e])}function Da(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(gA);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!hA.test(r)||rg.has(r)||!EA(o))return null;let i=PA(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function fd(n){let e=Da(n.trim());return!e||e.second!=="manager"?null:e}function IA(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function cg(n){let e=n.trim(),t=fd(e);if(t&&dd.has(t.first))return!0;if(ag(e)){let r=IA(e);return r!==null&&dd.has(r)}return!1}function md(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function hd(n){let e=n.trim();if(li(e))return Aa(e);let t=new Set;for(let r of ud(n)){ft(t,r);let o=Ia(r);o&&ft(t,o)}for(let r of pd(n))ft(t,r);for(let r of n.matchAll(fA))t.add(r[0]);for(let r of n.matchAll(mA))t.add(r[0]);for(let r of n.matchAll(pA))r[0].length>=4&&t.add(r[0]);return Yr([...t])}function lg(n){let e=n.trim();if(li(e))return Aa(e);let t=new Set,r=Da(e);r&&ft(t,r.camelCase);for(let o of hd(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Yr([...t])}function dg(n){return li(n)}var K={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 ug(n){return K.pureApiSymbol.test(n.trim())}function di(n){let e=n.trim();return K.stageModelExact.test(e)||K.stageModelEnglishExact.test(e)}function pg(n){let e=[];return di(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),K.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),K.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 fg(n){return di(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var AA=[{matches:n=>K.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>di(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!di(n)&&K.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>K.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>K.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>K.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>K.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>K.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=>K.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function DA(n,e){for(let{catalog:t,multiplier:r}of e){let o=yn[t];n.set(o,(n.get(o)??1)*r)}}function mg(n,e){for(let t of AA)t.matches(n)&&DA(e,t.weights)}function hg(n,e){if(e!==void 0)return!1;let t=n.trim();return ci(t)||K.pureApiSymbol.test(t)||cg(t)}function gg(n){let e=n.trim();if(ci(e)||K.pureApiSymbol.test(e))return"harmonyos-references";if(di(e)||K.uiAbilityLifecycleCatalog.test(e)||K.stateDecoratorCatalog.test(e)||K.stateManagement.test(e)||K.declarePermissionCatalog.test(e)||K.stageModelEntryPage.test(e)||K.routerRoute.test(e)||K.dialogPopupExact.test(e))return"harmonyos-guides"}import*as Kr from"fs";import*as wg from"path";var Ra=null,gd=null,yd=null;function RA(){return Kr.existsSync(Qo())}function TA(n){let e=Qo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};Kr.mkdirSync(wg.dirname(e),{recursive:!0}),ri(e),Kr.writeFileSync(e,JSON.stringify(t,null,2))}function kA(){if(Ra)return Ra;let n=er("harmonyos-stopwords.txt");return Ra=new Set(n.split(`
|
|
1309
|
+
`);o&&(e.isError?t.push(o):r.push(o))}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){g.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=>g.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,g.info("[restart] ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(e=>g.warn("Failed to re-init ArkTS project during restart:",e)))}restartCpp(){this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(e=>g.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,g.info("[restart] C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>g.warn("Failed to re-init C++ project during restart:",e)))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{g.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool=null,this.cppLspTool=null,this.cppLspManager&&(this.cppLspManager.dispose().catch(t=>{g.warn("Failed to dispose ClangdLspManager during setProjectPath:",t)}),this.cppLspManager=null),this.initPromise?(this.needsReinit=!0,g.info("Project path changed while ArkTS init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{g.warn("Failed to re-init project after setProjectPath:",t)})),this.cppInitPromise?(this.cppNeedsReinit=!0,g.info("Project path changed while C++ init is running, will reinit after current init completes")):(this.cppProjectState=0,this.cppHasNoCppCode=!1,this.cppInitRetryCount=0,this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.ensureCppProjectReady().catch(t=>{g.warn("Failed to re-init C++ project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new EI;if(await this.server.connect(e),g.info("devecocli-mcp-server started"),!this.config.debug){let t=Bu();t&&g.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Tt(t);r?(g.info(`Detected project path from client root: ${r}`),this.config.projectPath=r):g.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?g.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):g.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{g.warn("Background project init failed:",t)})}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return g.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return g.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){g.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,g.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{g.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{g.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{g.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Tt(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Tt(this.originalProjectPath),t&&g.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&await this.ensureProjectSynced()){this.ensureCppProjectReady().catch(e=>{g.warn("Background C++ project init failed:",e)}),this.projectState=3,this.arktsCheckTool=new _r(this.config.projectPath,this.config.toolProvider,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{g.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,g.info("Project fully initialized, check tool is available")}catch(e){g.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=Qm(e),r=!t.required;return g.info(`Sync check: skipHvigor=${r}, reason=${t.reason}`),this.runSync(e,{skipHvigorSync:r})}async runSync(e,t){this.projectState=2,g.info("Starting project sync...");let r=await Mr.handleSyncProject(e,this.config.toolProvider,t);switch(r.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let o=Date.now()-this.syncSkipStartedAt,i=Math.round(o/1e3);return o>=jl?(g.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(g.warn(`Sync skipped: ${r.reason}, resetting to IDLE for retry (elapsed ${i}s / ${jl/1e3}s)`),this.projectState=0,!1)}case"failed":return g.error(`Project sync failed: ${r.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1;default:return g.error(`Project sync: unknown status ${r.status}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}async ensureCppProjectReady(){if(!this.cppInitPromise){this.cppInitPromise=this.doEnsureCppProjectReady();try{await this.cppInitPromise}finally{this.cppInitPromise=null}this.cppNeedsReinit&&(this.cppNeedsReinit=!1,this.cppProjectState=0,this.ensureCppProjectReady().catch(e=>{g.warn("Failed to re-init C++ project after cppNeedsReinit:",e)}))}}async doEnsureCppProjectReady(){let e=this.config.projectPath;if(!e){g.info("[Cpp] No project path, skipping C++ init");return}this.cppProjectState=1;let t=Fn(e);if(t.length===0){g.info('[Cpp] No C++ modules found, C++ tools will return "no C++ code"'),this.cppHasNoCppCode=!0,this.cppProjectState=4,this.cppInitRetryCount=0;return}if(this.cppHasNoCppCode=!1,g.info(`[Cpp] Found ${t.length} C++ module(s): ${t.map(r=>r.name).join(", ")}`),!!await this.runSyncCpp(e)){this.cppProjectState=3,this.cppLspManager=new Jo({workspaceRoot:e,toolProvider:this.config.toolProvider});try{await this.cppLspManager.start(),this.cppCheckTool=new jr(this.cppLspManager,this.config.toolProvider),this.cppLspTool=new $r(this.cppLspManager),this.cppProjectState=4,this.cppInitRetryCount=0,g.info("[Cpp] C++ project fully initialized, C++ tools are available")}catch(r){g.error("[Cpp] C++ LSP initialization failed:",r),this.cppLspManager&&this.cppLspManager.dispose().catch(()=>{}),this.cppLspManager=null,this.cppCheckTool=null,this.cppLspTool=null,this.cppInitRetryCount++,this.cppProjectState=5}}}async runSyncCpp(e){this.cppProjectState=2,g.info("[Cpp] Starting C++ project sync (compileNative)...");let t=await Jo.handleSyncCppProject(e,this.config.toolProvider);switch(t.status){case"success":return this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,!0;case"skipped":{this.cppSyncSkippedDueToLock=!0,this.cppSyncSkipStartedAt===0&&(this.cppSyncSkipStartedAt=Date.now());let r=Date.now()-this.cppSyncSkipStartedAt,o=Math.round(r/1e3);return r>=jl?(g.error(`[Cpp] C++ sync skipped for ${o}s due to lock contention, giving up`),this.cppInitRetryCount++,this.cppSyncSkipStartedAt=0,this.cppProjectState=5,!1):(g.warn(`[Cpp] C++ sync skipped: ${t.reason}, resetting to IDLE_CPP for retry (elapsed ${o}s)`),this.cppProjectState=0,!1)}case"failed":return g.error(`[Cpp] C++ project sync failed: ${t.reason}`),this.cppSyncSkippedDueToLock=!1,this.cppSyncSkipStartedAt=0,this.cppInitRetryCount++,this.cppProjectState=5,!1}return!1}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppLspManager&&await this.cppLspManager.dispose(),this.cppCheckTool=null,this.cppLspTool=null;try{await this.server.close()}catch(e){g.warn("Failed to close MCP server connection:",e)}g.info("devecocli-mcp-server stopped"),Uu(),$u()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function PI(n){let e=[],t=[],r=[];for(let o of n)mn.extname(o).toLowerCase()===".ets"?e.push(o):On(o)?t.push(o):r.push(o);return{etsFiles:e,cppFiles:t,unsupported:r}}function Ul(n){return new pa(n)}import*as Bl from"fs";import*as hn from"path";import{spawn as CI}from"child_process";async function nh(n){_n(!1);let{serverPath:e,logPath:t,projectPath:r,serverMaxSize:o}=await II(n),i=RI(e,t,r,n.toolProvider,o);g.info("ace-server started, bridging stdio (initialize is left to the client)"),kI(i)}async function II(n){b()||n.toolProvider.require({clt:!1});let e;if(n.projectPath)e=pe(hn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let a=Bi(process.cwd());e=pe(a??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${a??"null, fallback to cwd"}`)}else e=pe(process.cwd()),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.sdkPath,r=n.toolProvider.lspServerPath;r||(g.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=hn.resolve(hn.dirname(r),"standardIndex","index.js"),i=hn.join(nn(),"lsp-server",String(Date.now()));Bl.mkdirSync(i,{recursive:!0});let s=AI(e,t);return g.info(`projectPath=${e}, sdkPath=${t}, serverPath=${o}, logPath=${i}, serverMaxSize=${s}MB`),{projectPath:e,serverPath:o,logPath:i,serverMaxSize:s}}function AI(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,o=Number.isFinite(r)&&r>0?r:void 0,i=DI(n,e),s=Yi(i,o);return g.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${i}, override=${o??"none"})`),s}function DI(n,e){try{let t=[];return new Jn(n,e).getAllDependencyMap(t).status==="OK"?t.length:new kt(n).getAllModuleInfo().length}catch{return 0}}function RI(n,e,t,r,o){let i=hn.join(e,"lspLog");Bl.mkdirSync(i,{recursive:!0});let s=TI(n,i,t,r.sdkPath,o),a=r.nodePath;return g.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),CI(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function TI(n,e,t,r,o){let i=U(e);return["--expose-gc",`--max-old-space-size=${o}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,n,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE",`--projectPath=${U(t)}`,`--sdkPath=${U(r)}`]}function kI(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`ace-server exited with code ${e}`),process.exit(e??0)})}import*as rh from"fs";import*as Yn from"path";import{spawn as xI}from"child_process";async function oh(n){_n(!1);let{clangdPath:e,compileCommandsDir:t,projectPath:r}=await NI(n),o=Yn.join(t,"compile_commands.json");rh.existsSync(o)||g.warn(`compile_commands.json not found at ${o}. Cross-file navigation/completion will be limited. Run \`devecocli build\` first to generate it.`);let i=LI(e,t,r);g.info("clangd started, bridging stdio (initialize is left to the client)"),MI(i)}async function NI(n){let e;if(n.projectPath)e=pe(Yn.resolve(n.projectPath)),g.info(`projectPath=specified ('${e}'), no search`);else if(n.autoDetect){let i=Bi(process.cwd());e=pe(i??process.cwd()),g.info(`findHarmonyProjectInDir('${process.cwd()}') => ${i??"null, fallback to cwd"}`)}else e=pe(Yn.resolve(process.cwd())),g.info(`projectPath=cwd ('${e}'), no search (pass --auto-detect to search subdirs)`);let t=n.toolProvider.clangdPath;t||(g.error("clangd not found in DevEco Studio SDK. Expected at <deveco>/sdk/default/openharmony/native/llvm/bin/clangd"),process.exit(1));let r=sr(e),o=Yn.dirname(r);return g.info(`projectPath=${e}, clangdPath=${t}, compileCommandsDir=${o}`),{projectPath:e,clangdPath:t,compileCommandsDir:o}}function LI(n,e,t){let r=OI(e);return g.info(`[serve-lsp-cpp] spawn: ${n} ${r.join(" ")}`),xI(n,r,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function OI(n){return[`--compile-commands-dir=${U(n)}`,"--log=info","--pch-storage=memory"]}function MI(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{g.error(`[clangd] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{g.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{g.info(`clangd exited with code ${e}`),process.exit(e??0)})}async function FI(){let n=process.env.PROJECT_PATH||"",e=process.env.NODE_MAX_OLD_SPACE_SIZE,t=process.env.DEBUG==="true"||process.env.DEBUG==="1",r=await I.new();b()||r.require({clt:!1});let i=Ul({toolProvider:r,projectPath:n,nodeMaxOldSpaceSize:e,debug:t}),s=async()=>{await i.shutdown(),process.exit(0)};process.once("SIGINT",s),process.once("SIGTERM",s),process.platform==="win32"&&process.once("SIGBREAK",s);try{await i.start()}catch(a){console.error("Failed to start MCP server:",a),process.exit(1)}}var Wl=new _I("serve").description("Host bundled auxiliary protocol servers");Wl.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await FI()});Wl.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));let e=await I.new();n.arkts?await nh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):n.cpp?await oh({toolProvider:e,projectPath:n.projectPath,autoDetect:n.autoDetect}):(console.error("Use --arkts or --cpp to specify which language server to start."),process.exit(1))});var ih=Wl;import{Command as HR,InvalidArgumentError as Ld}from"commander";import{red as $a,dim as $R}from"colorette";import*as re from"fs";import*as Et from"path";import PR from"adm-zip";import CR from"proper-lockfile";import fy from"ora";import*as pt from"fs";import*as oi from"path";var gn=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Kn={"harmonyos-guides":"\u5F00\u53D1\u6307\u5357","harmonyos-references":"API\u53C2\u8003","best-practices":"\u6700\u4F73\u5B9E\u8DF5","harmonyos-faqs":"FAQ","harmonyos-releases":"\u7248\u672C\u8BF4\u660E","harmonyos-roadmap":"\u53D8\u66F4\u9884\u544A"};var Br="1.9.1",qV=48*1024*1024,sh=280,ah=6,ch=100,lh=3,dh=28,Gl=10,uh=/API参考|APIReference/i,Yo=200,ph=12,fh=4,ql=8,mh=6,fa=700,Vl=250,zl=400,hh=1320,gh=120,yh=450,wh=250,vh=500,Sh=480,bh=80,Eh=200,Ph=60,Ch=200,Ih=40,Ah=200,Dh=200,Rh=40,Wr=500,Th=Object.fromEntries(gn.map((n,e)=>[Kn[n],e])),yn=Object.fromEntries(gn.map((n,e)=>[n,e]));import*as Ko from"fs";import*as O from"path";import{fileURLToPath as Lh}from"url";import*as wn from"fs";import*as kh from"path";import{homedir as jI}from"os";var HI="deveco-cli",Jl,Xn=class extends Error{constructor(e){super(e),this.name="CliDataDirError"}};function $I(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Ni(n)!==""}function xh(){let n=process.env.DEVECO_CLI_DATA_DIR,t=(n===void 0||n===""?"":Ni(n))||kh.join(jI(),".local","share",HI);try{return Li(t)}catch(r){throw new Xn(r instanceof Error?r.message:String(r))}}async function Nh(){let n=xh();await wn.promises.mkdir(n,{recursive:!0});let e;try{e=await wn.promises.realpath(n)}catch(r){throw new Xn(`DEVECO_CLI_DATA_DIR is not usable: ${r instanceof Error?r.message:String(r)}`)}if(!(await wn.promises.stat(e)).isDirectory())throw new Xn("DEVECO_CLI_DATA_DIR must be a writable directory.");return Jl=e,e}function ma(n){let e=Gr();return $I()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function Gr(){if(Jl!==void 0)return Jl;let n=xh();try{if(wn.existsSync(n))return wn.realpathSync(n)}catch{}return n}var UI="docs";function qr(){return O.join(Gr(),UI)}function Q(){return O.join(qr(),".index")}function ha(){return O.join(Q(),"build.lock")}function Xo(){return O.join(Q(),"build-status.json")}function Vr(){return O.join(Q(),"build-meta.json")}function Zn(){return O.join(Q(),"search.db")}function Zo(){return O.join(Q(),"sqlite-backend.json")}function Qo(){return O.join(Q(),"jieba-backend.json")}function Gt(){return O.join(Q(),".tmp")}function BI(){return O.join(Gr(),"logs")}function zr(){return O.join(BI(),"doc-init.log")}function WI(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function Oh(n,e){return O.dirname(WI(n,e))}function Mh(){let n=Lh(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?Oh(n,e):O.join(e,"..","..","..")}function GI(...n){let e=Lh(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(Oh(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function _h(...n){let e=Mh(),t=Ko.realpathSync(e);for(let r of GI(...n))try{let o=Ko.lstatSync(r);if(o.isSymbolicLink()||!o.isFile())throw new Error(`Unsafe documentation package asset: ${n.join("/")} must be a regular file.`);let i=Ko.realpathSync(r);if(!co(i,t))throw new Error(`Unsafe documentation package asset: ${n.join("/")} is outside the package.`);return i}catch(o){if(o.code!=="ENOENT")throw o}return null}function vn(){return _h("docs.zip")}function Yl(){return _h("index.zip")}function Fh(){return O.join(Mh(),"index","data")}import*as qt from"fs";import*as Qn from"path";var Vt=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ga=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function jh(n){return n instanceof ga}var Kl=null;function Xl(n){Kl=n}function Zl(){if(Kl)return Kl;let n=Q();if(Vt.every(o=>qt.existsSync(Qn.join(n,o))))return n;let t=Fh();if(Vt.every(o=>qt.existsSync(Qn.join(t,o))))return t;throw new ga("Lexicon files not found. Install the documentation index first (index.zip).")}function Hh(){Zl()}function er(n){let e=Qn.join(Zl(),n);return qt.readFileSync(e,"utf-8")}function $h(n,e){return qt.readFileSync(Qn.join(e,n),"utf-8")}async function Uh(n,e=Zl()){await qt.promises.mkdir(n,{recursive:!0});for(let t of Vt){let r=Qn.join(e,t),o=Qn.join(n,t);await qt.promises.copyFile(r,o)}}import*as ya from"fs";import*as Bh from"path";import*as Wh from"yauzl";var ei=null;function qI(n){return new Promise((e,t)=>{Wh.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,o)=>{if(r||!o){t(r??new Error(`Failed to open zip: ${n}`));return}e(o)})})}function VI(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function zI(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",o=>{let i=VI(o);i.endsWith("/")||e.set(i,o),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function JI(){ei?.zipfile.close(),ei=null}async function YI(n){let e=Bh.resolve(n),t=await ya.promises.stat(e),r=ei;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;JI();let o=await qI(e),i=await zI(o);return ei={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:o,entries:i,readChain:Promise.resolve()},ei}function KI(n,e){return new Promise((t,r)=>{n.openReadStream(e,(o,i)=>{if(o||!i){r(o??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];i.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),i.on("end",()=>{t(Buffer.concat(s))}),i.on("error",r)})})}async function XI(n,e){let t=n.readChain,r;n.readChain=new Promise(o=>{r=o}),await t;try{return await KI(n.zipfile,e)}finally{r()}}function ZI(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 QI(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function Gh(n){let e=vn();if(!e)throw new Error("docs.zip not found");let t=await YI(e),r=QI(t.entries,ZI(n));if(!r)throw new Error(`Document not found: ${n}`);return(await XI(t,r)).toString("utf-8")}function Ql(){let n=vn();return n!==null&&ya.existsSync(n)}import*as he from"fs";import*as zt from"path";import qh from"adm-zip";import*as ti from"fs";import*as va from"path";var wa=class extends Error{constructor(e){super(`Unsafe documentation path: ${e}`),this.name="DocPathSafetyError"}};function ni(n){return n instanceof Xn||n instanceof wa||n instanceof Error&&(n.name==="CliDataDirError"||n.name==="DocPathSafetyError")}function nd(n){return new wa(n)}function eA(){return yt(Gr())}function td(n,e,t){let r=xi(n,e);if(r===null)throw nd(`${t} resolves outside the data directory.`);return r}async function ed(n,e){await ti.promises.mkdir(n,{recursive:!0});let t=td(n,e,"directory");if(!(await ti.promises.stat(t)).isDirectory())throw nd("path must be a directory.")}function ri(n){let e=eA();try{let t=td(n,e,"file");if(!ti.statSync(t).isFile())throw nd("path must be a regular file.")}catch(t){if(t.code==="ENOENT"){td(va.dirname(n),e,"file parent");return}throw t}}async function Jr(n={}){let e=n.mode??"write",t=await Nh();await ed(qr(),t),await ed(Q(),t),e==="write"&&await ed(Gt(),t);for(let r of[Zn(),Vr(),Xo(),ha(),Qo(),Zo(),...Vt.map(o=>va.join(Q(),o))])ri(r)}var rd=["search.db","build-meta.json",...Vt],tA=["corpus.json","corpus-offsets.json","orama.dpack"];async function nA(n){for(let e of tA)await he.promises.rm(zt.join(n,e),{force:!0})}async function rA(n){let e=await he.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await he.promises.rm(zt.join(n,t.name),{recursive:!0,force:!0})}function Vh(n){let t=new qh(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 oA(n){let e=Q();await he.promises.mkdir(e,{recursive:!0});for(let t of rd){let r=zt.join(e,t);await he.promises.rm(r,{force:!0}),await he.promises.rename(zt.join(n,t),r)}await nA(e),await he.promises.rm(Gt(),{recursive:!0,force:!0})}function zh(n){let e=Yl();if(!e)return!1;try{let t=Vh(e);return t.indexVersion===Br&&t.docsZipSha256===n&&t.segmentCount>0}catch{return!1}}async function Jh(n){await Jr({mode:"write"});let e=Yl();if(!e)throw new Error("index.zip not found");let t=Vh(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=Gt();await he.promises.rm(r,{recursive:!0,force:!0}),await he.promises.mkdir(r,{recursive:!0});let o=new qh(e);for(let s of rd){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await he.promises.writeFile(zt.join(r,s),a.getData())}let i=JSON.parse(await he.promises.readFile(zt.join(r,"build-meta.json"),"utf-8"));if(!he.existsSync(zt.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await oA(r),await he.promises.mkdir(qr(),{recursive:!0}),await rA(qr()),i}async function Yh(){await he.promises.rm(Gt(),{recursive:!0,force:!0});let n=Q();for(let e of rd)await he.promises.rm(zt.join(n,e),{force:!0})}import{createHash as Kh}from"crypto";import*as Xh from"fs";async function Sa(n){return new Promise((e,t)=>{let r=Kh("sha256"),o=Xh.createReadStream(n);o.on("data",i=>r.update(i)),o.on("error",t),o.on("end",()=>e(r.digest("hex")))})}function Zh(n){return Kh("sha256").update(n,"utf8").digest("hex")}var od=null;function iA(){let n=er("harmonyos-synonyms.json");return JSON.parse(n)}function sA(n){let e=new Map;for(let t of n){let r=t.map(o=>o.trim()).filter(Boolean);for(let o of r){let i=r.filter(s=>s!==o);e.set(o.toLowerCase(),i),o!==o.toLowerCase()&&e.set(o,i)}}return e}function aA(){let n=sA(iA()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function cA(){return od||(od=aA()),od}function id(n,e){let t=cA(),r=n.split(/\s+/).filter(Boolean),o=new Set,i=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&o.size<i;s+=1){let a=r[s];o.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(o.size>=i)break;o.add(l)}}return[...o].join(" ")}function Qh(n,e){let t=e?$h(n,e):er(n);return Zh(t)}function ba(n){return Qh("harmonyos-synonyms.json",n)}function Ea(n){return Qh("harmonyos-terms.txt",n)}var lA={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Pa(){try{let n=await pt.promises.readFile(Xo(),"utf-8");return JSON.parse(n)}catch{return{...lA}}}async function sd(n){let e=Xo();await pt.promises.mkdir(oi.dirname(e),{recursive:!0}),await pt.promises.writeFile(e,JSON.stringify(n,null,2))}function eg(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Sn(n){let t={...await Pa(),...n,updatedAt:Date.now()};return await sd(t),t}async function ad(){let n=vn();return n?Sa(n):null}async function cd(){try{let n=await pt.promises.readFile(Vr(),"utf-8");return JSON.parse(n)}catch{return null}}async function Ca(n=!1){if(n)return"no-index";let e=await cd();if(!e||e.segmentCount===0)return"no-index";let t=await ad();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==Br?"engine-upgraded":e.termsHash!==Ea()?"terms-changed":e.synonymsHash!==ba()?"synonyms-changed":null}function ii(){if(!Ql()||!pt.existsSync(Zn())||!pt.existsSync(Vr()))return!1;let n=oi.dirname(Zn());if(!Vt.every(e=>pt.existsSync(oi.join(n,e))))return!1;try{let e=pt.readFileSync(Vr(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function ld(n=!1){return n?!0:Ql()?ii()?await Ca()!==null:!0:!1}async function tg(){let n=await Pa();return["installing","indexing","persisting"].includes(n.state)}import*as Ee from"fs";import*as sy from"os";import*as _e from"path";var ng=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),dd=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),rg=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"]),og=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 dA=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,uA=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,pA=/[A-Z][a-zA-Z0-9]{2,}/g,fA=/@[A-Z][a-zA-Z0-9]*/g,mA=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ig=6,hA=/^[a-z][a-z0-9]{2,}$/,gA=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,yA=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,wA=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,vA=/^[A-Z][a-zA-Z0-9]+$/;function SA(n){return`"${n.replace(/"/g,'""')}"`}function ai(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(SA).join(` ${e} `)}function si(n){return ai(n,"OR")}function sg(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?si([...t,...r]):`(${si(t)}) AND (${si(r)})`}function ci(n){return yA.test(n)}function ag(n){return wA.test(n)&&n.length>=ig}function bA(n){return vA.test(n)}function li(n){return ci(n)||ag(n)||bA(n)}function EA(n){let e=n.trim().toLowerCase();return og.has(e)?!1:ng.has(e)}function PA(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function Ia(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function ud(n){return[...n.matchAll(dA)].map(e=>e[0])}function pd(n,e=ig){let t=[];for(let r of n.matchAll(uA))r[0].length>=e&&t.push(r[0]);return t}function Yr(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>t.length&&o.endsWith(t)&&t.length>=4})})}function ft(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function CA(n){let e=new Set;ft(e,n);let t=Ia(n);return t&&ft(e,t),Yr([...e])}function Aa(n){if(ci(n))return CA(n);let e=new Set;return ft(e,n),Yr([...e])}function Da(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(gA);if(!t)return null;let r=t[1].toLowerCase(),o=t[2].toLowerCase();if(!hA.test(r)||rg.has(r)||!EA(o))return null;let i=PA(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function fd(n){let e=Da(n.trim());return!e||e.second!=="manager"?null:e}function IA(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function cg(n){let e=n.trim(),t=fd(e);if(t&&dd.has(t.first))return!0;if(ag(e)){let r=IA(e);return r!==null&&dd.has(r)}return!1}function md(n,e,t){let r=t.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let i of[n,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function hd(n){let e=n.trim();if(li(e))return Aa(e);let t=new Set;for(let r of ud(n)){ft(t,r);let o=Ia(r);o&&ft(t,o)}for(let r of pd(n))ft(t,r);for(let r of n.matchAll(fA))t.add(r[0]);for(let r of n.matchAll(mA))t.add(r[0]);for(let r of n.matchAll(pA))r[0].length>=4&&t.add(r[0]);return Yr([...t])}function lg(n){let e=n.trim();if(li(e))return Aa(e);let t=new Set,r=Da(e);r&&ft(t,r.camelCase);for(let o of hd(e))t.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&t.add(i)}return Yr([...t])}function dg(n){return li(n)}var K={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 ug(n){return K.pureApiSymbol.test(n.trim())}function di(n){let e=n.trim();return K.stageModelExact.test(e)||K.stageModelEnglishExact.test(e)}function pg(n){let e=[];return di(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),K.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),K.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 fg(n){return di(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var AA=[{matches:n=>K.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>di(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!di(n)&&K.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>K.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>K.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>K.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>K.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>K.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=>K.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function DA(n,e){for(let{catalog:t,multiplier:r}of e){let o=yn[t];n.set(o,(n.get(o)??1)*r)}}function mg(n,e){for(let t of AA)t.matches(n)&&DA(e,t.weights)}function hg(n,e){if(e!==void 0)return!1;let t=n.trim();return ci(t)||K.pureApiSymbol.test(t)||cg(t)}function gg(n){let e=n.trim();if(ci(e)||K.pureApiSymbol.test(e))return"harmonyos-references";if(di(e)||K.uiAbilityLifecycleCatalog.test(e)||K.stateDecoratorCatalog.test(e)||K.stateManagement.test(e)||K.declarePermissionCatalog.test(e)||K.stageModelEntryPage.test(e)||K.routerRoute.test(e)||K.dialogPopupExact.test(e))return"harmonyos-guides"}import*as Kr from"fs";import*as wg from"path";var Ra=null,gd=null,yd=null;function RA(){return Kr.existsSync(Qo())}function TA(n){let e=Qo(),t={backend:"jieba-wasm",reason:"native-jieba-load-failed",message:n,createdAt:new Date().toISOString()};Kr.mkdirSync(wg.dirname(e),{recursive:!0}),ri(e),Kr.writeFileSync(e,JSON.stringify(t,null,2))}function kA(){if(Ra)return Ra;let n=er("harmonyos-stopwords.txt");return Ra=new Set(n.split(`
|
|
1310
1310
|
`).map(e=>e.trim()).filter(Boolean)),Ra}function xA(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let o=n[t+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),t+=1;continue}e.push(r)}return e}function vg(n){let e=kA(),t=[];for(let r of xA(n)){let o=r.trim();!o||e.has(o)||(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&t.push(o))}return t}async function Sg(n){let{dict:e}=await import("@node-rs/jieba/dict.js"),t=n.withDict(e),r=er("harmonyos-terms.txt");return t.loadDict(Buffer.from(r,"utf-8")),t}async function NA(){let{Jieba:n}=await import("@node-rs/jieba");return Sg(n)}async function yg(){let{Jieba:n}=await import("@node-rs/jieba-wasm32-wasi");return Sg(n)}async function LA(){let n=await import("jieba-wasm"),e=er("harmonyos-terms.txt");return n.with_dict(e),{cut:n.cut,cutForSearch:n.cut_for_search}}async function OA(){if(b())return LA();if(RA())return yg();try{let e=await NA();return m("doc-index: using @node-rs/jieba backend"),e}catch(e){let t=e instanceof Error?e.message:String(e);TA(t),m(`doc-index: @node-rs/jieba unavailable (${t}); falling back to wasm32-wasi`)}let n=await yg();return m("doc-index: using @node-rs/jieba-wasm32-wasi backend"),n}async function bn(){return gd||(yd||(yd=OA().then(n=>(gd=n,n))),yd)}async function MA(n){let e=await bn();return vg(e.cutForSearch(n,!0))}async function bg(n){let e=await bn();return vg(e.cut(n,!0))}async function Ta(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await MA(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function _A(n,e){let t=[];for(let o of n){let i=o.trim();i&&(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&t.push(i))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ka(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Sh:hh,o=e?Eh:yh,i=e?await _A(n.apiSymbols,o):await Ta(n.apiSymbols.join(" "),o),a=(await Promise.all([Ta(t,e?bh:gh),Promise.resolve(i),Ta(n.headingsText,e?Ph:wh),Ta(n.bodySample,e?Ch:vh)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function FA(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,Yo)}function wd(n,e){let t=new Set,r=[];for(let o of[...n,...e]){let i=o.toLowerCase();if(!(!o||t.has(i))&&(t.add(i),r.push(o),r.length>=ph))break}return r}function jA(n){return n.length>=2&&n.length<=fh}function HA(n,e){let t=id(n,ql),r=t.split(/\s+/).filter(Boolean),o=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],i=[e.second,e.lower,e.camelCase],s=wd(o,i);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:sg(o,i)}}function $A(n,e){let t=wd(Aa(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:si(t)}}async function Eg(n){let e=FA(n),t=e.trim(),r=fg(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let o=Da(t);if(o)return HA(e,o);if(li(t))return $A(e,t);let i=pg(e),s=[...hd(e),...i],c=dg(t)?e:id(e,ql),l=await bg(c),d=wd(s,l);return{rawQuery:e,expandedQuery:c,tokens:d,preferAnd:i.length===0&&jA(d)}}var Pg=["harmonyos-releases","harmonyos-roadmap"],UA=new Set(Pg.map(n=>yn[n])),BA=Pg.map(n=>`${Kn[n]}/`);function WA(n){return UA.has(n)}function GA(n){return BA.some(e=>n.startsWith(e))}function Cg(n){let e=[],t=[];for(let r of n)WA(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Ig(n){let e=[],t=[];for(let r of n)GA(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var qA=[{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 ui(n,e,t){let r=yn[e];n.set(r,(n.get(r)??1)*t)}function VA(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(o||i)){ui(e,"harmonyos-guides",1.45),ui(e,"harmonyos-references",1.35);return}(o||i)&&ui(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&ui(e,"harmonyos-references",1.75)}function Ag(n){let e=new Map,t=n.trim();if(!t)return e;let r=ug(t);VA(t,e),mg(t,e);for(let o of qA)o.pattern.test(t)&&(o.skipForPureApiSymbol&&r||ui(e,o.catalog,o.multiplier));return e}function Dg(n){return gg(n)}import*as Zr from"fs";import*as Mg from"path";var zA=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function Rg(n,e){let t=-1;for(let r of zA){let o=n.lastIndexOf(r);o>t&&(t=o)}return t>=e?t:-1}function Tg(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),o=Rg(r,e-20),i=o>=0?o:e;return{text:t.slice(0,i).trimEnd(),excerptTruncated:!0}}function kg(n,e,t={}){let{maxLen:r=Dh,contextChars:o=Rh,excerptTruncated:i=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(Ue=>Ue.trim()).filter(Boolean),c=0;for(let Ue of a){let nt=s.toLowerCase().indexOf(Ue.toLowerCase());if(nt>=0){c=nt;break}}let l=Math.max(0,c-o),d=Math.min(s.length,l+r),h=s.slice(l,d),w=Rg(h,r-25);w>=0&&(d=l+w);let S=s.slice(l,d).trim(),A=l>0?"...":"",se=d<s.length||i?"...":"";return`${A}${S}${se}`}var JA=`
|
|
1311
1311
|
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
1312
1312
|
d.catalog_id, bm25(segments_fts) AS bm25
|
|
@@ -1377,40 +1377,40 @@ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
|
1377
1377
|
Detail: ${n.message}`):n}try{await bn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new hi(`${bR()}
|
|
1378
1378
|
|
|
1379
1379
|
Detail: ${e}`)}try{await pi()}catch(n){let e=n instanceof Error?n.message:String(n);throw new hi(ER(e))}}var Td=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function IR(n){return new Promise(e=>setTimeout(e,n))}async function my(n){let e=zr();await re.promises.mkdir(Et.dirname(e),{recursive:!0}),await re.promises.appendFile(e,`${new Date().toISOString()} ${n}
|
|
1380
|
-
`)}async function AR(n){let e=vn();if(!e)throw new Error("docs.zip not found");await re.promises.rm(n,{recursive:!0,force:!0}),await re.promises.mkdir(n,{recursive:!0});let t=Et.resolve(n),r=new PR(e);for(let o of r.getEntries()){let i=Et.resolve(t,o.entryName);if(!co(i,t))throw new Error(`Unsafe docs.zip entry path: ${o.entryName}`);if(o.isDirectory){await re.promises.mkdir(i,{recursive:!0});continue}await re.promises.mkdir(Et.dirname(i),{recursive:!0}),await re.promises.writeFile(i,o.getData())}await ly(n)}async function DR(){await Jr({mode:"write"});let n=Q(),e=Gt(),t=await re.promises.readdir(e);for(let r of t){let o=Et.join(n,r);await re.promises.rm(o,{force:!0}),await re.promises.rename(Et.join(e,r),o)}await re.promises.rm(e,{recursive:!0,force:!0}),await re.promises.rm(Et.join(n,"orama.dpack"),{force:!0})}async function uy(n,e,t){e?.start(t),await Sn({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Jh(n),Qr(),e&&(e.text="Documentation index installed.")}async function RR(n,e){try{return await uy(n,e,"Installing documentation index\u2026"),await kd(e),!0}catch(t){if(ni(t))throw t}try{return await Yh(),Qr(),await uy(n,e,"Retrying documentation index install\u2026"),await kd(e),!0}catch(t){if(ni(t))throw t;let r=t instanceof Error?t.message:String(t);return await my(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function TR(n,e,t){let r=Gt(),o=await cy();await re.promises.mkdir(Q(),{recursive:!0}),await re.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Sn({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await AR(o),await ay({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:Ea(),synonymsHash:ba(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Sn({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await re.promises.rm(o,{recursive:!0,force:!0})}await Sn({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await DR(),Qr()}async function kd(n){await Sn({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function kR(n){let e=await cd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Sn({state:"done",message:t,error:null})}async function xR(n,e){let t=n instanceof Error?n.message:String(n);throw await Sn({state:"error",error:t}),await my(`ERROR: ${t}`),e?.fail(t),n}async function NR(){let n=Q();await re.promises.mkdir(n,{recursive:!0});let e=ha();return re.existsSync(e)||await re.promises.writeFile(e,"","utf-8"),e}async function LR(){let n=await NR();return CR.lock(n,{stale:1800*1e3})}async function OR(){let n=vn(),e=(n?await Sa(n):null)??await ad();if(!e)throw new Error("docs.zip not found");return e}async function MR(n,e){let t=await OR(),r=n.force||await ld(n.force),o=await Ca(n.force);if(!r&&!o&&ii()){await kR(e);return}!n.force&&zh(t)&&await RR(t,e)||(await TR(n,t,e),await kd(e))}var gi=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:fy({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await Jr({mode:"write"}),i=await LR(),await sd(eg("Starting documentation setup\u2026")),await MR(e,o)}catch(s){throw i&&await xR(s,o),s}finally{i&&await i()}}};async function _R(n){for(;;){let e=await Pa();if(e.state==="done"&&ii())return;if(e.state==="error")throw new Td("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 IR(500)}}async function py(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await gi.run({builtBy:"doc-init",force:e,quiet:!0})}async function FR(){let n=await Ca()!==null;if(ii()&&!n)return;let e=fy({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await tg()){await _R(e),e.succeed("Documentation ready.");return}if(await ld()){await py(e),e.succeed("Documentation ready.");return}await py(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function yi(){await Jr({mode:"read"}),await FR(),await dy()}function jR(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 xd=class{async search(e,t,r=20){await yi();try{return await Dd(e,t,r)}catch(o){if(!jR(o))throw o;return Qr(),await gi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Dd(e,t,r)}}async readDocument(e){return await yi(),Gh(e)}},Nd=new xd;function hy(...n){return e=>{if(!n.includes(e))throw new Ld(`Allowed values: ${n.join(", ")}`);return e}}function UR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Ld("Must be a positive integer.");return e}var BR=hy("json","default"),WR=hy("json","default");function Od(n){let e=n instanceof Error?n.message:String(n);return ni(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 Ua=new HR("docs").description("Search and read HarmonyOS documentation from local docs directory");Ua.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",qR,"all").option("--format <fmt>","Output format (default, json)",BR,"default").option("--limit <n>","Max number of results",UR,20).action(async(n,e)=>{try{let t=GR(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Nd.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):VR(o)}catch(t){console.error($a(Od(t))),process.exit(1)}});Ua.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error($a("Document ID cannot be empty.")),process.exit(1));let t=await Nd.readDocument(e);console.log(t)}catch(e){console.error($a(Od(e))),process.exit(1)}});Ua.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",WR,"default").action(async n=>{try{if(await yi(),n.format==="json"){let e=gn.map(t=>({name:t,title:Kn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of gn)console.log(` ${e.padEnd(20)} ${$R(Kn[e])}`)}catch(e){console.error($a(Od(e))),process.exit(1)}});function GR(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>Yo)throw new Error(`Query exceeds ${Yo} characters.`);return e}function qR(n){if(n==="all")return"all";if(!gn.includes(n))throw new Ld(`Invalid catalog "${n}". Allowed: all, ${gn.join(", ")}`);return n}function VR(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 gy=Ua;import{Command as
|
|
1381
|
-
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),S=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:S})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===i}))}function yy(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function wi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function wy(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 vy(n){return n.originalText||void 0}function eo(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let o=r.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)r.push(o.children[i])}return t}function Sy(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:o,parent:i,depth:s}=r.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let w={...o,children:[]};if(a?t.push(w):i.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=o.children.length-1;w>=0;w--)r.push({current:o.children[w],parent:d,depth:h})}return t}function ZR(n){let e=JR(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function QR(n){return n.attributes??{}}function Ba(n,e,t){let r=QR(n),o={id:r.id||void 0,type:r.type||void 0,text:vy(r),bounds:wy(r.bounds),clickable:wi(r.clickable)||void 0,longClickable:wi(r.longClickable)||void 0,scrollable:wi(r.scrollable)||void 0,checkable:wi(r.checkable)||void 0,hitTestBehavior:yy(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>Ba(i,e,t+1))),o}function eT(n,e){if(e){let r=n.find(o=>String(o.id)===e);if(!r){let o=n.map(i=>`${i.id} (${i.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${o||"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 tr=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 o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];r!==void 0&&i.push("-d",String(r)),t&&i.push("-w",t),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await ae(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let r=XR(KR(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),ZR(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await ae(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),YR(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await ae(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new Jt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=eT(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).map(s=>Ba(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let o=[];for(let i of r){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:Ba(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>Sy(Ba(s,0,0),t))}};var Wa={left:"0",right:"1",up:"2",down:"3"};function Te(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Md(n,e){n!==void 0&&Te(n,e)}function by(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ga(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function vi(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 Ey(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Py(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 to(n,e,t,r,o=!0){by(n,e),Ga(t,"--id"),Md(n,"x"),Md(e,"y"),Ey(r),Py(n!==void 0,!!t,!!r,o)}async function Pn(n,e){let r=await new Ir(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Pt(n){let e=await I.new(),t=await Pn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function no(n,e,t,r,o,i){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Jt(n,e).listWindows({all:!0}),c=new tr(n);return tT(c,e,a,o,i)}async function tT(n,e,t,r,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new Error(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,o,!1);return rT(s,r)}return nT(n,e,t,r)}async function nT(n,e,t,r){let o=[...new Set(t.map(a=>a.displayId))],i=await n.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of eo([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 Cy(s[0].node,r)}function rT(n,e){let t=eo(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 Cy(t[0],e)}function Cy(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function Ze(n,e,t){let r=["-t",e,"shell"
|
|
1380
|
+
`)}async function AR(n){let e=vn();if(!e)throw new Error("docs.zip not found");await re.promises.rm(n,{recursive:!0,force:!0}),await re.promises.mkdir(n,{recursive:!0});let t=Et.resolve(n),r=new PR(e);for(let o of r.getEntries()){let i=Et.resolve(t,o.entryName);if(!co(i,t))throw new Error(`Unsafe docs.zip entry path: ${o.entryName}`);if(o.isDirectory){await re.promises.mkdir(i,{recursive:!0});continue}await re.promises.mkdir(Et.dirname(i),{recursive:!0}),await re.promises.writeFile(i,o.getData())}await ly(n)}async function DR(){await Jr({mode:"write"});let n=Q(),e=Gt(),t=await re.promises.readdir(e);for(let r of t){let o=Et.join(n,r);await re.promises.rm(o,{force:!0}),await re.promises.rename(Et.join(e,r),o)}await re.promises.rm(e,{recursive:!0,force:!0}),await re.promises.rm(Et.join(n,"orama.dpack"),{force:!0})}async function uy(n,e,t){e?.start(t),await Sn({state:"installing",phase:1,phaseLabel:"Installing index",message:t}),await Jh(n),Qr(),e&&(e.text="Documentation index installed.")}async function RR(n,e){try{return await uy(n,e,"Installing documentation index\u2026"),await kd(e),!0}catch(t){if(ni(t))throw t}try{return await Yh(),Qr(),await uy(n,e,"Retrying documentation index install\u2026"),await kd(e),!0}catch(t){if(ni(t))throw t;let r=t instanceof Error?t.message:String(t);return await my(`Bundled index install failed; falling back to local rebuild: ${r}`),!1}}async function TR(n,e,t){let r=Gt(),o=await cy();await re.promises.mkdir(Q(),{recursive:!0}),await re.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Sn({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await AR(o),await ay({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:Ea(),synonymsHash:ba(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Sn({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await re.promises.rm(o,{recursive:!0,force:!0})}await Sn({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await DR(),Qr()}async function kd(n){await Sn({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function kR(n){let e=await cd(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Sn({state:"done",message:t,error:null})}async function xR(n,e){let t=n instanceof Error?n.message:String(n);throw await Sn({state:"error",error:t}),await my(`ERROR: ${t}`),e?.fail(t),n}async function NR(){let n=Q();await re.promises.mkdir(n,{recursive:!0});let e=ha();return re.existsSync(e)||await re.promises.writeFile(e,"","utf-8"),e}async function LR(){let n=await NR();return CR.lock(n,{stale:1800*1e3})}async function OR(){let n=vn(),e=(n?await Sa(n):null)??await ad();if(!e)throw new Error("docs.zip not found");return e}async function MR(n,e){let t=await OR(),r=n.force||await ld(n.force),o=await Ca(n.force);if(!r&&!o&&ii()){await kR(e);return}!n.force&&zh(t)&&await RR(t,e)||(await TR(n,t,e),await kd(e))}var gi=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:fy({text:"Checking documentation\u2026",color:"cyan"}),i;try{e.assumeStorageSafe||await Jr({mode:"write"}),i=await LR(),await sd(eg("Starting documentation setup\u2026")),await MR(e,o)}catch(s){throw i&&await xR(s,o),s}finally{i&&await i()}}};async function _R(n){for(;;){let e=await Pa();if(e.state==="done"&&ii())return;if(e.state==="error")throw new Td("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 IR(500)}}async function py(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await gi.run({builtBy:"doc-init",force:e,quiet:!0})}async function FR(){let n=await Ca()!==null;if(ii()&&!n)return;let e=fy({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await tg()){await _R(e),e.succeed("Documentation ready.");return}if(await ld()){await py(e),e.succeed("Documentation ready.");return}await py(e,!0),e.succeed("Documentation ready.")}catch(t){throw e.fail(t.message),t}}async function yi(){await Jr({mode:"read"}),await FR(),await dy()}function jR(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 xd=class{async search(e,t,r=20){await yi();try{return await Dd(e,t,r)}catch(o){if(!jR(o))throw o;return Qr(),await gi.run({builtBy:"doc-init",force:!0,quiet:!0,assumeStorageSafe:!0}),Dd(e,t,r)}}async readDocument(e){return await yi(),Gh(e)}},Nd=new xd;function hy(...n){return e=>{if(!n.includes(e))throw new Ld(`Allowed values: ${n.join(", ")}`);return e}}function UR(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new Ld("Must be a positive integer.");return e}var BR=hy("json","default"),WR=hy("json","default");function Od(n){let e=n instanceof Error?n.message:String(n);return ni(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 Ua=new HR("docs").description("Search and read HarmonyOS documentation from local docs directory");Ua.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",qR,"all").option("--format <fmt>","Output format (default, json)",BR,"default").option("--limit <n>","Max number of results",UR,20).action(async(n,e)=>{try{let t=GR(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await Nd.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):VR(o)}catch(t){console.error($a(Od(t))),process.exit(1)}});Ua.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error($a("Document ID cannot be empty.")),process.exit(1));let t=await Nd.readDocument(e);console.log(t)}catch(e){console.error($a(Od(e))),process.exit(1)}});Ua.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",WR,"default").action(async n=>{try{if(await yi(),n.format==="json"){let e=gn.map(t=>({name:t,title:Kn[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of gn)console.log(` ${e.padEnd(20)} ${$R(Kn[e])}`)}catch(e){console.error($a(Od(e))),process.exit(1)}});function GR(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>Yo)throw new Error(`Query exceeds ${Yo} characters.`);return e}function qR(n){if(n==="all")return"all";if(!gn.includes(n))throw new Ld(`Invalid catalog "${n}". Allowed: all, ${gn.join(", ")}`);return n}function VR(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 gy=Ua;import{Command as JT}from"commander";import{Command as oT,InvalidArgumentError as iT,Option as _d}from"commander";import{readFileSync as JR,unlinkSync as YR}from"fs";import{tmpdir as KR}from"os";import{join as XR}from"path";var Jt=class{constructor(e,t){this.hdcPath=e;this.serial=t}hdcPath;serial;async listWindows(e){let t=await this.fetchDump(),r=zR(t);return e?.all||(r=r.filter(o=>o.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 ae(this.hdcPath,e);if(t.exitCode!==0)throw new Error(`Failed to query windows: ${(t.stderr||t.stdout).trim()}`);return t.stdout}};function zR(n){let e=n.split(`
|
|
1381
|
+
`),t=e.findIndex(s=>s.trimStart().startsWith("WindowName"));if(t===-1)return[];let r=[];for(let s=t+1;s<e.length;s++){let a=e[s].trim();if(!a||/^-+$/.test(a)||a.startsWith("Focus window")||a.startsWith("total window"))break;let c=a.split(/\s+/);if(c.length<5)continue;let l=c[0],d=Number(c[1]),h=Number(c[2]),w=Number(c[3]),S=Number(c[4]);Number.isFinite(w)&&Number.isFinite(d)&&Number.isFinite(h)&&r.push({id:w,name:l,pid:h,displayId:d,type:S})}let o=e.find(s=>s.trim().startsWith("Focus window")),i=o?Number(o.replace(/.*:\s*/,"").trim()):NaN;return r.map(s=>({...s,focused:s.id===i}))}function yy(n){if(!(!n||n==="HitTestMode.Default"))return n.startsWith("HitTestMode.")?n.slice(12):n}function wi(n){if(!(n==null||n==="")){if(typeof n=="boolean")return n;if(n==="true")return!0;if(n==="false")return!1}}function wy(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 vy(n){return n.originalText||void 0}function eo(n,e){let t=[],r=[...n].reverse();for(;r.length>0;){let o=r.pop();o.id===e&&t.push(o);for(let i=o.children.length-1;i>=0;i--)r.push(o.children[i])}return t}function Sy(n,e){let t=[],r=[{current:n,parent:null,depth:0}];for(;r.length>0;){let{current:o,parent:i,depth:s}=r.pop(),a=i===null,c=!o.id&&!o.text&&!o.clickable&&!o.longClickable&&!o.scrollable&&!o.checkable,l=a||!c,d=i;if(l){let w={...o,children:[]};if(a?t.push(w):i.children.push(w),d=w,e>0&&s+1>=e)continue}if(process.env.DEVECO_CLI_DEBUG){let w=o.type?o.id?`${o.type}#${o.id}`:o.type:"#";m(`collapse ${w} depth=${s} -> ${a?"root":c?"collapsed":"emitted"}`)}let h=l?s+1:s;for(let w=o.children.length-1;w>=0;w--)r.push({current:o.children[w],parent:d,depth:h})}return t}function ZR(n){let e=JR(n,"utf-8").trim();if(!e)throw new Error("Empty dumpLayout response from device");return JSON.parse(e)}function QR(n){return n.attributes??{}}function Ba(n,e,t){let r=QR(n),o={id:r.id||void 0,type:r.type||void 0,text:vy(r),bounds:wy(r.bounds),clickable:wi(r.clickable)||void 0,longClickable:wi(r.longClickable)||void 0,scrollable:wi(r.scrollable)||void 0,checkable:wi(r.checkable)||void 0,hitTestBehavior:yy(r.hitTestBehavior),children:[]};return e>0&&t+1>=e||n.children&&(o.children=n.children.map(i=>Ba(i,e,t+1))),o}function eT(n,e){if(e){let r=n.find(o=>String(o.id)===e);if(!r){let o=n.map(i=>`${i.id} (${i.name})`).join(", ");throw new Error(`Window '${e}' not found. Available windows: ${o||"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 tr=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 o=this.buildRemoteDumpPath(),i=["-t",e,"shell","uitest","dumpLayout","-p",o];r!==void 0&&i.push("-d",String(r)),t&&i.push("-w",t),m(`Executing: ${this.hdcPath} ${i.join(" ")}`);let s=await ae(this.hdcPath,i);if(s.exitCode!==0)throw new Error(`Failed to dump layout: ${(s.stderr||s.stdout).trim()}`);return this.recvAndParseDump(e,o)}async recvAndParseDump(e,t){let r=XR(KR(),`deveco_cli_dump_${Date.now()}_${process.pid}.json`);try{return await this.recvDumpFile(e,t,r),ZR(r)}finally{await this.cleanupDumpArtifacts(e,r,t)}}async recvDumpFile(e,t,r){let o=["-t",e,"file","recv",t,r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`);let i=await ae(this.hdcPath,o);if(i.exitCode!==0)throw new Error(`Failed to recv dump file: ${(i.stderr||i.stdout).trim()}`)}async cleanupDumpArtifacts(e,t,r){try{m(`Removing local dump file: ${t}`),YR(t)}catch(i){m(`Failed to clean local dump file ${t}: ${i.message}`)}let o=["-t",e,"shell","rm","-f",r];m(`Executing: ${this.hdcPath} ${o.join(" ")}`),await ae(this.hdcPath,o).catch(i=>{m(`Failed to clean remote dump file ${r}: ${i.message}`)})}async dumpRawNodes(e,t,r){let i=await new Jt(this.hdcPath,e).listWindows({all:!0});if(r){let a=[...new Set(i.map(l=>l.displayId))],c=[];for(let l of a)c.push(await this.fetchRawDump(e,void 0,l));return c}let s=eT(i,t);return[await this.fetchRawDump(e,String(s.id),s.displayId)]}async dumpFullTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).map(s=>Ba(s,t,0))}async dumpFullTreeByDisplays(e,t,r){let o=[];for(let i of r){let s=await this.fetchRawDump(e,void 0,i);o.push({displayId:i,tree:Ba(s,t,0)})}return o}async dumpCollapsedTree(e,t,r,o){return(await this.dumpRawNodes(e,r,o)).flatMap(s=>Sy(Ba(s,0,0),t))}};var Wa={left:"0",right:"1",up:"2",down:"3"};function Te(n,e){let t=Number(n);if(!Number.isInteger(t)||t<=0)throw new Error(`${e} must be a positive integer`)}function Md(n,e){n!==void 0&&Te(n,e)}function by(n,e){if(n===void 0!=(e===void 0))throw new Error("x and y must be provided together")}function Ga(n,e){if(n!==void 0&&n.length===0)throw new Error(`${e} must not be empty`)}function vi(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 Ey(n){if(n!==void 0&&!/^[a-zA-Z0-9_-]+$/.test(n))throw new Error("--window must consist of letters, digits, - or _")}function Py(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 to(n,e,t,r,o=!0){by(n,e),Ga(t,"--id"),Md(n,"x"),Md(e,"y"),Ey(r),Py(n!==void 0,!!t,!!r,o)}async function Pn(n,e){let r=await new Ir(n).selectDevice(e);if(!r)throw new Error("No device selected. Use `devecocli device list` to see targets.");return r}async function Pt(n){let e=await I.new(),t=await Pn(e,n);return{hdcPath:e.hdcPath,deviceId:t}}async function no(n,e,t,r,o,i){if(t!==void 0&&r!==void 0)return{x:t,y:r};if(o===void 0)throw new Error("Either provide x y coordinates or use --id");let a=await new Jt(n,e).listWindows({all:!0}),c=new tr(n);return tT(c,e,a,o,i)}async function tT(n,e,t,r,o){if(o!==void 0){let i=t.find(a=>String(a.id)===o);if(i&&i.displayId!==0)throw new Error(`Window "${o}" is on display ${i.displayId}. The current command only supports operations on the primary display.`);let s=await n.dumpFullTree(e,0,o,!1);return rT(s,r)}return nT(n,e,t,r)}async function nT(n,e,t,r){let o=[...new Set(t.map(a=>a.displayId))],i=await n.dumpFullTreeByDisplays(e,0,o),s=[];for(let{displayId:a,tree:c}of i)for(let l of eo([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 Cy(s[0].node,r)}function rT(n,e){let t=eo(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 Cy(t[0],e)}function Cy(n,e){let t=n.bounds;if(!t)throw new Error(`Node "${e}" has no bounds.`);let[r,o,i,s]=t;return{x:Math.ceil((r+i)/2),y:Math.ceil((o+s)/2)}}async function Ze(n,e,t){let r=["-t",e,"shell",t.join(" ")];m(`Executing: ${n} ${r.join(" ")}`);let o=await ae(n,r);if(o.exitCode!==0)throw new Error(o.stderr||o.stdout||`uitest exited with code ${o.exitCode}`);let i=o.stdout.toLowerCase();if(["illegal","fail","error","incorrect","please confirm that the coordinate values are correct"].some(a=>i.includes(a))&&!i.includes("no error"))throw new Error(o.stdout.trim()||"uitest command failed")}import sT from"ora";function aT(n){let e=parseInt(n,10);if(!Number.isInteger(e)||e<0||String(e)!==n.trim())throw new iT("depth must be a non-negative integer");return e}function cT(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 Iy(n,e=0){let t=[],r=" ".repeat(e);for(let o of n)t.push(`${r}${cT(o)}`),o.children.length>0&&t.push(...Iy(o.children,e+1).split(`
|
|
1382
1382
|
`));return t.join(`
|
|
1383
1383
|
`)}function lT(n){if(n.allWindows&&n.window)throw new Error("--all-windows and --window are mutually exclusive.")}function dT(n,e){let t=eo(n,e);if(t.length===0)throw new Error(`Node '${e}' not found.`);let r=t.map(o=>({...o,children:[]}));console.log(JSON.stringify(r,null,2))}function uT(n,e){console.log(e==="json"?JSON.stringify(n,null,2):Iy(n))}async function pT(n){lT(n);let e=sT({text:"Dumping layout\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),o=await Pn(r,n.device),i=new tr(r.hdcPath);t=n.mode==="full"?await i.dumpFullTree(o,n.depth,n.window,n.allWindows):await i.dumpCollapsedTree(o,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){dT(t,n.id);return}uT(t,n.format)}var Ay=new oT("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 _d("--depth <n>","Tree depth limit (0=unlimited, 1=root only, 2=root+children)").argParser(aT).default(0)).addOption(new _d("--format <format>","Output format").choices(["default","json"]).default("default")).addOption(new _d("--mode <mode>","Output mode: full | simplified").choices(["full","simplified"]).default("simplified")).action(async n=>{await pT(n)});import{Command as fT,Option as mT}from"commander";import{yellow as hT}from"colorette";import gT from"ora";var yT=["Id","Name","Pid","DisplayId","Focused"];function wT(n,e){if(e==="json"){let r=n.map(o=>({id:o.id,name:o.name,pid:o.pid,displayId:o.displayId,focused:o.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(Lt(yT,t))}async function vT(n){let e=gT({text:"Listing windows\u2026",color:"cyan"}).start(),t;try{let r=await I.new(),o=await Pn(r,n.device);t=await new Jt(r.hdcPath,o).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(hT(" No windows found."));return}wT(t,n.format)}var Fd=new fT("window").description("Manage device windows");Fd.command("list").description("List windows on the device").option("--device <name|serial>","Target device (name or serial)").addOption(new mT("--format <format>","Output format").choices(["default","json"]).default("default")).option("--all","Show all windows including system windows").action(async n=>{await vT(n)});import{Command as ST}from"commander";import Fe from"fs";import Qe from"path";import{randomUUID as bT}from"crypto";import{green as ET}from"colorette";function PT(){return String(Date.now())}function Dy(n){let e;try{e=Fe.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{Fe.accessSync(n,Fe.constants.W_OK|Fe.constants.X_OK)}catch(t){throw new Error(`Screenshot directory is not writable: ${n}`,{cause:t})}}function Ry(n,e){try{throw Fe.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 CT(n){if(!n?.trim())throw new Error("--path is required.");let e=n.trim(),t=Qe.resolve(e);try{if(Fe.statSync(t).isDirectory()){Dy(t);let o=Qe.join(t,`screenshot-${PT()}.png`);return Ry(o,t),o}}catch(o){if(o.code!=="ENOENT")throw o}if(Qe.extname(t).toLowerCase()!==".png")throw new Error(`Screenshot path must be an existing directory or a PNG file: ${t}`);let r=Qe.dirname(t);return Dy(r),Ry(t,r),t}function Ty(n){if(!Fe.existsSync(n))throw new Error(`Screenshot file was not created: ${n}`);let e=Fe.statSync(n);if(!e.isFile()||e.size===0)throw new Error(`Screenshot file is empty: ${n}`);let t=Fe.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 IT(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 AT(n){let e=n.trim();if(!/^\d+$/.test(e))throw new Error("--display must be a non-negative integer.");return e}function DT(n,e){try{Fe.copyFileSync(n,e,Fe.constants.COPYFILE_EXCL)}catch(t){throw t.code==="EEXIST"?new Error(`Screenshot file already exists: ${e}`,{cause:t}):t}Ty(e)}function RT(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 TT(n){let e=["-t",n.serial,"shell","ls","-l",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`);let t=await ae(n.hdcPath,e);return t.exitCode===0?RT(t.stdout):void 0}function kT(n){return[n.stdout,n.stderr].filter(Boolean).join(`
|
|
1384
1384
|
`).trim()}function xT(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 NT(n,e){let t=IT(n,e);m(`Executing: ${n.hdcPath} ${t.join(" ")}`);let r=await ae(n.hdcPath,t),o=await TT(n);return{created:o!==void 0&&o>0,output:kT(r)}}async function LT(n){let e="";for(let t of[void 0,"png"]){let r=await NT(n,t);if(r.created)return;if(n.display!==void 0&&xT(r.output))throw new Error(`Screenshot was not created on device: ${n.remotePath}.
|
|
1385
1385
|
snapshot_display output:
|
|
1386
1386
|
${r.output}`);r.output&&(e=r.output)}throw new Error(e?`Screenshot was not created on device: ${n.remotePath}.
|
|
1387
1387
|
snapshot_display output:
|
|
1388
|
-
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function ky(n){try{return Ty(n),!0}catch{return!1}}function xy(n){let e=[];for(let t of Fe.readdirSync(n,{withFileTypes:!0})){let r=Qe.join(n,t.name);if(t.isDirectory()){e.push(...xy(r));continue}t.isFile()&&ky(r)&&e.push(r)}return e}function OT(n,e){let t=Qe.join(n,Qe.basename(e));if(ky(t))return t;let r=xy(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function jd(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await ae(n.hdcPath,r);return o.exitCode!==0&&m(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),OT(e,n.remotePath)}async function MT(n){let e=Fe.mkdtempSync(Qe.join(Qe.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await jd(n,e,Qe.join(e,Qe.basename(n.remotePath)))??await jd(n,e,e)??await jd(n,e,Qe.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);DT(t,n.localPath)}finally{Fe.rmSync(e,{recursive:!0,force:!0})}}async function _T(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await ae(n.hdcPath,e)}async function FT(n){try{await LT(n),await MT(n)}finally{await _T(n)}}async function jT(n){let e=CT(n.path),t=n.display!==void 0?AT(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let r=await I.new(),o=await Pn(r,n.device),i=`/data/local/tmp/devecocli-${bT()}.png`;await FT({hdcPath:r.hdcPath,serial:o,localPath:e,remotePath:i,display:t}),console.log(ET(`Screenshot saved to ${e}`))}var Ny=new ST("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(jT);import{Command as Cn}from"commander";async function In(n,e,t){let r=new dt;r.start(n);try{await t(r)}catch(o){throw r.stop(),new Error(`${e}: ${o.message}`,{cause:o})}}async function
|
|
1388
|
+
${e}`:`Screenshot was not created on device: ${n.remotePath}.`)}function ky(n){try{return Ty(n),!0}catch{return!1}}function xy(n){let e=[];for(let t of Fe.readdirSync(n,{withFileTypes:!0})){let r=Qe.join(n,t.name);if(t.isDirectory()){e.push(...xy(r));continue}t.isFile()&&ky(r)&&e.push(r)}return e}function OT(n,e){let t=Qe.join(n,Qe.basename(e));if(ky(t))return t;let r=xy(n);if(r.length===1)return r[0];if(r.length>1)throw new Error(`Multiple screenshot files were received in ${n}.`)}async function jd(n,e,t){let r=["-t",n.serial,"file","recv",n.remotePath,t];m(`Executing: ${n.hdcPath} ${r.join(" ")}`);let o=await ae(n.hdcPath,r);return o.exitCode!==0&&m(`hdc file recv failed: ${o.stderr||o.stdout||`exit code ${o.exitCode}`}`),OT(e,n.remotePath)}async function MT(n){let e=Fe.mkdtempSync(Qe.join(Qe.dirname(n.localPath),".devecocli-screenshot-"));try{let t=await jd(n,e,Qe.join(e,Qe.basename(n.remotePath)))??await jd(n,e,e)??await jd(n,e,Qe.join(e,"screenshot.png"));if(!t)throw new Error(`Screenshot file was not created in ${e}.`);DT(t,n.localPath)}finally{Fe.rmSync(e,{recursive:!0,force:!0})}}async function _T(n){let e=["-t",n.serial,"shell","rm","-f",n.remotePath];m(`Executing: ${n.hdcPath} ${e.join(" ")}`),await ae(n.hdcPath,e)}async function FT(n){try{await LT(n),await MT(n)}finally{await _T(n)}}async function jT(n){let e=CT(n.path),t=n.display!==void 0?AT(n.display):void 0;if(n.device!==void 0&&!n.device.trim())throw new Error("--device must not be empty.");let r=await I.new(),o=await Pn(r,n.device),i=`/data/local/tmp/devecocli-${bT()}.png`;await FT({hdcPath:r.hdcPath,serial:o,localPath:e,remotePath:i,display:t}),console.log(ET(`Screenshot saved to ${e}`))}var Ny=new ST("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(jT);import{Command as Cn}from"commander";function HT(n){let t=`"$(printf '%s' '${Buffer.from(n,"utf8").toString("base64")}' | base64 -d)"`;return m(`escapeShellText: ${n} -> ${t}`),t}async function In(n,e,t){let r=new dt;r.start(n);try{await t(r)}catch(o){throw r.stop(),new Error(`${e}: ${o.message}`,{cause:o})}}async function $T(n,e,t){await In("Executing click...","click failed",async r=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Pt(t.device),{x:s,y:a}=await no(o,i,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ze(o,i,["uitest","uiInput","click",String(s),String(a)]),r.succeed(`click at (${s}, ${a})`)})}async function UT(n,e,t){await In("Executing doubleclick...","doubleclick failed",async r=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Pt(t.device),{x:s,y:a}=await no(o,i,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ze(o,i,["uitest","uiInput","doubleClick",String(s),String(a)]),r.succeed(`doubleclick at (${s}, ${a})`)})}async function BT(n,e,t){await In("Executing longclick...","longclick failed",async r=>{to(n,e,t.id,t.window);let{hdcPath:o,deviceId:i}=await Pt(t.device),{x:s,y:a}=await no(o,i,n!==void 0?Number(n):void 0,e!==void 0?Number(e):void 0,t.id,t.window);await Ze(o,i,["uitest","uiInput","longClick",String(s),String(a)]),r.succeed(`longclick at (${s}, ${a})`)})}async function WT(n,e,t,r,o){await In("Executing swipe...","swipe failed",async i=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let s=vi(o.speed),{hdcPath:a,deviceId:c}=await Pt(o.device),l=["uitest","uiInput","swipe",n,e,t,r];s&&l.push(s),await Ze(a,c,l),i.succeed(`swipe from (${n}, ${e}) to (${t}, ${r})`)})}async function GT(n,e,t,r,o){await In("Executing fling...","fling failed",async i=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let s=vi(o.speed),{hdcPath:a,deviceId:c}=await Pt(o.device),l=["uitest","uiInput","fling",n,e,t,r];s&&l.push(s),await Ze(a,c,l),i.succeed(`fling from (${n}, ${e}) to (${t}, ${r})`)})}async function qT(n,e,t,r,o){await In("Executing drag...","drag failed",async i=>{Te(n,"x1"),Te(e,"y1"),Te(t,"x2"),Te(r,"y2");let s=vi(o.speed),{hdcPath:a,deviceId:c}=await Pt(o.device),l=["uitest","uiInput","drag",n,e,t,r];s&&l.push(s),await Ze(a,c,l),i.succeed(`drag from (${n}, ${e}) to (${t}, ${r})`)})}async function VT(n,e){await In("Executing dircfling...","dircfling failed",async t=>{let r=Wa[n];if(r===void 0)throw new Error(`Invalid direction "${n}". Valid values: ${Object.keys(Wa).join(", ")}`);let{hdcPath:o,deviceId:i}=await Pt(e.device);await Ze(o,i,["uitest","uiInput","dircFling",r]),t.succeed(`dircfling ${n}`)})}async function zT(n,e,t,r){await In("Executing text input...","input failed",async o=>{to(e,t,r.id,r.window,!1),Ga(n,"text");let{hdcPath:i,deviceId:s}=await Pt(r.device),a=HT(n);if(e!==void 0)await Ze(i,s,["uitest","uiInput","inputText",`${e}`,`${t}`,a]),o.succeed(`input ${n} at (${e}, ${t})`);else if(r.id){let{x:c,y:l}=await no(i,s,void 0,void 0,r.id,r.window);await Ze(i,s,["uitest","uiInput","inputText",`${c}`,`${l}`,a]),o.succeed(`input ${n} at (${c}, ${l})`)}else await Ze(i,s,["uitest","uiInput","text",a]),o.succeed(`input ${n}`)})}var Ly=new Cn("click").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action($T),Oy=new Cn("doubleclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Double-tap at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(UT),My=new Cn("longclick").argument("[x]","X coordinate").argument("[y]","Y coordinate").description("Long-press at the specified coordinates").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id (auto-resolves to center coordinates)").option("--window <windowId>","Target window id (used with --id)").action(BT),_y=new Cn("swipe").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Swipe from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(WT),Fy=new Cn("fling").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Fling from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(GT),jy=new Cn("drag").argument("<x1>","Start X coordinate").argument("<y1>","Start Y coordinate").argument("<x2>","End X coordinate").argument("<y2>","End Y coordinate").description("Drag from one point to another").option("--device <name|serial>","Target device (name or serial)").option("--speed <n>","Swipe speed (pixels per second)").action(qT),Hy=new Cn("dircfling").argument("<direction>","Direction: up, down, left, right").description("Fling in a specified direction").option("--device <name|serial>","Target device (name or serial)").action(VT),$y=new Cn("text").argument("<text>","Text to input").argument("[x]","Optional X coordinate").argument("[y]","Optional Y coordinate").description("Input text at a target location or the currently focused field").option("--device <name|serial>","Target device (name or serial)").option("--id <id>","Node id to target before input (auto-resolves to center)").option("--window <windowId>","Target window id (used with --id)").action(zT);var et=new JT("ui").description("Inspect and interact with UI on a connected device");et.addCommand(Ay);et.addCommand(Fd);et.addCommand(Ny);et.addCommand(Ly);et.addCommand(Oy);et.addCommand(My);et.addCommand(_y);et.addCommand(Fy);et.addCommand(jy);et.addCommand(Hy);et.addCommand($y);var Uy=et;import{Command as Nx}from"commander";import{execa as gk}from"execa";import Yt from"fs";import*as Bd from"os";import*as B from"path";var YT=new RegExp("\x1B\\[[0-?]*[ -/]*[@-~]","g"),KT=/\r/g,XT=/^(Working|Finished)\.\.\.\[[^\]]*\]\d+%$/,ZT=/^<+\s*/,QT=/\s*>+$/,ek=[/^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 Hd(n){if(!n)return"";let e=n.replace(YT,"").replace(KT,`
|
|
1389
1389
|
`).split(`
|
|
1390
|
-
`).map(t=>t.trimEnd()).filter(t=>
|
|
1390
|
+
`).map(t=>t.trimEnd()).filter(t=>nk(t));return e.length>0?`${e.join(`
|
|
1391
1391
|
`)}
|
|
1392
|
-
`:""}function qy(n){let e=Hd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Vy(e))return{jsonText:e,diagnostics:""};let t=
|
|
1392
|
+
`:""}function qy(n){let e=Hd(n).trim();if(!e)return{jsonText:void 0,diagnostics:""};if(Vy(e))return{jsonText:e,diagnostics:""};let t=rk(e);if(!t)return{jsonText:void 0,diagnostics:`${e}
|
|
1393
1393
|
`};let r=[e.slice(0,t.start).trim(),e.slice(t.end).trim()].filter(Boolean).join(`
|
|
1394
1394
|
`);return{jsonText:e.slice(t.start,t.end),diagnostics:r?`${r}
|
|
1395
|
-
`:""}}function
|
|
1395
|
+
`:""}}function tk(n){return XT.test(n.trim())}function nk(n){let e=n.trim();return!!e&&!tk(e)&&!ek.some(t=>t.test(e))}function Vy(n){try{return JSON.parse(n),!0}catch{return!1}}function rk(n){for(let e=0;e<n.length;e++){if(n[e]!=="["&&n[e]!=="{")continue;let t=ok(n,e);if(t)return t}}function ok(n,e){for(let t=n.length;t>e;t--){let r=n[t-1];if(r!=="]"&&r!=="}")continue;let o=n.slice(e,t);if(Vy(o))return{start:e,end:t}}}var By=["Error","Warning","Suggestion","Info","Off","Unknown"];function zy(n){let e=$d(n);return{issues:ck(e),summary:ik(n,e)}}function ik(n,e){let t=dk(e);return{filesChecked:uk(n).size,issues:e.length,errors:t.get("Error")??0,warnings:t.get("Warning")??0,suggestions:t.get("Suggestion")??0}}function $d(n,e=""){if(Array.isArray(n))return n.flatMap(i=>$d(i,e));if(!Jy(n))return[];let t=Si(n,["filePath","file","path"])??e,r=sk(n,t);if(r.length>0)return r;let o=ak(n,t);return o?[o]:[]}function sk(n,e){let t=["messages","defects","issues","results","files"];for(let r of t){let o=n[r];if(Array.isArray(o)){let i=o.flatMap(s=>$d(s,e));if(i.length>0)return i}}return[]}function ak(n,e){let t=Si(n,["message","description","desc","detail"])??"",r=hk(Si(n,["rule","ruleId","ruleName"])),o=fk(n,["severity","level"]),i=Si(n,["filePath","file","path"])??e;if(!(!t&&!r&&o==="Unknown"))return{file:i,line:Gy(n,["line","reportLine"]),column:Gy(n,["column","reportColumn"]),severity:o,rule:r,message:t}}function ck(n){return[...n].sort((e,t)=>{let r=Wy(e.severity)-Wy(t.severity);return r===0?lk(e,t):r})}function lk(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 dk(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 uk(n){let e=new Set;return Ud(e,n,""),e}function Ud(n,e,t){if(Array.isArray(e)){for(let o of e)Ud(n,o,t);return}if(!Jy(e))return;let r=Si(e,["filePath","file","path"])??t;r&&n.add(r),pk(n,e,r)}function pk(n,e,t){let r=["messages","defects","issues","results","files"];for(let o of r){let i=e[o];if(Array.isArray(i))for(let s of i)Ud(n,s,t)}}function fk(n,e){for(let t of e){let r=n[t];if(typeof r=="string"||typeof r=="number")return mk(r)}return"Unknown"}function mk(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 hk(n){let e=n?.normalize("NFKC").trim();if(e)return e.replace(ZT,"").replace(QT,"").toLowerCase()}function Wy(n){let e=By.indexOf(n);return e===-1?By.length:e}function Si(n,e){for(let t of e){let r=n[t];if(typeof r=="string")return r}}function Gy(n,e){for(let t of e){let r=n[t];if(typeof r=="number")return r}}function Jy(n){return typeof n=="object"&&n!==null}var Yy="deveco-codelinter-",Ky=[".ets",".ts",".js"],bi=class n{resolution;cwd;constructor(e,t){this.resolution=n.resolveWithToolProvider(e),this.cwd=t}static resolveProjectRoot(e){try{return G.discover(e).rootDir}catch{return e}}async check(e){let t=Yt.mkdtempSync(B.join(Bd.tmpdir(),Yy)),r=B.join(t,"report.json");try{let o=n.resolveProjectRoot(this.cwd),i=this.resolveLintTarget(e.lintPath,o),s=this.resolveConfigPath(e.configPath,i),a=this.buildNativeArgs(e,i.path,s,r),c=await this.run(a),l=qy(c.stdout),d=l.diagnostics+Hd(c.stderr);try{let h=this.readJsonReport(r,l.jsonText);return{exitCode:c.exitCode,diagnostics:d,report:zy(h)}}catch(h){return{exitCode:c.exitCode,diagnostics:d,reportError:h}}}finally{this.removeTempDir(t)}}resolveLintTarget(e,t){let r=e?B.resolve(this.cwd,e):t,o=this.resolveRealPath(r,"Lint path"),i=Yt.statSync(o);if(!i.isFile()&&!i.isDirectory())throw new Error(`Lint path must be a file or directory: ${r}`);if(i.isFile()){let a=B.extname(o).toLowerCase();if(!Ky.some(l=>l===a))throw new Error(`Unsupported lint file extension "${a||"<none>"}": ${o}. Supported extensions: ${Ky.join(", ")}.`)}let s=this.discoverProjectRoot(o,i.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): ${o}`);return{path:o,projectRoot:s}}resolveConfigPath(e,t){let r=e?B.resolve(this.cwd,e):B.join(t.projectRoot??this.cwd,"code-linter.json5"),o=this.resolveRealPath(r,"`--config-path`");if(!Yt.statSync(o).isFile())throw new Error(`--config-path must point to a file: ${r}`);if(t.projectRoot){let i=this.discoverProjectRoot(o,!1);if(i===void 0||B.relative(t.projectRoot,i)!=="")throw new Error(`\`--config-path\` must belong to the same project as the lint path. Lint project: ${t.projectRoot}; Config project: ${i??"not found"}.`)}return o}discoverProjectRoot(e,t){let r=t?e:B.dirname(e);try{return Yt.realpathSync(G.discover(r).rootDir)}catch{return}}resolveRealPath(e,t){try{return Yt.realpathSync(e)}catch(r){throw new Error(`${t} does not exist or cannot be resolved: ${e}`,{cause:r})}}buildNativeArgs(e,t,r,o){let i=["--config",r];return e.fix&&i.push("--fix"),e.incremental&&i.push("--incremental"),i.push("--product",e.product,"--format","json","--output",o,t),i}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 o=await gk(this.resolution.command,t,{cwd:r,env:this.resolution.env,stdout:"pipe",stderr:"pipe",reject:!1});return{exitCode:o.exitCode??1,stdout:o.stdout,stderr:o.stderr}}prepareRuntimeDirectories(){for(let e of this.resolution.runtimeDirectories??[])Yt.mkdirSync(e,{recursive:!0})}readJsonReport(e,t){let o=(Yt.existsSync(e)?Yt.readFileSync(e,"utf-8").trim():void 0)||t?.trim();if(!o)throw new Error("Native JSON report was not generated.");return JSON.parse(o)}removeTempDir(e){let t=B.resolve(e),r=B.resolve(Bd.tmpdir());!(t.startsWith(`${r}${B.sep}`)||t===r)||!B.basename(t).startsWith(Yy)||Yt.rmSync(t,{recursive:!0,force:!0})}static resolveWithToolProvider(e){let t=n.getSource(e),r=e.toolchainRoot,o=e.codelinterPath,i=e.sdkPath,s=n.getPathEntries(e,t),a=t==="ide"?"DevEco Studio":"DevEco Command Line Tools",c={command:e.nodePath,argsPrefix:[o,i],env:{...process.env,PATH:[...s,process.env.PATH||""].join(B.delimiter),DEVECO_SDK_HOME:i}};return t==="command-line-tools"&&(c.workingDirectory=r,c.runtimeDirectories=[n.getResultDirectory(o)]),m(`[CodelinterAdapter] Selected ${a} entry: ${o}`),c}static getPathEntries(e,t){let r=[B.dirname(e.nodePath)];return t==="ide"&&e.javaPath&&r.unshift(B.dirname(e.javaPath)),r}static getResultDirectory(e){return B.resolve(e,"..","linter","result")}static getSource(e){return e.sourceType==="studio"?"ide":"command-line-tools"}};import{red as Va,yellow as Dk}from"colorette";import{Argument as Rk,Command as Tk,InvalidArgumentError as Dn}from"commander";import Pi from"fs";import*as je from"path";import*as Ei from"path";var Xy="n/a",Zy=/\\/g,yk=/\|/g,wk=/\r?\n/g;function Qy(n,e){if(n.issues.length===0)return`No defects found.
|
|
1396
1396
|
${Wd(n.summary)}
|
|
1397
|
-
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[
|
|
1397
|
+
`;let t=e===void 0?n.issues:n.issues.slice(0,e),r=[Sk(t),Wd(n.summary)];return e!==void 0&&t.length<n.issues.length&&r.push(vk(n.issues.length,t.length)),`${r.join(`
|
|
1398
1398
|
`)}
|
|
1399
1399
|
`}function ew(n,e){return[Wd(n.summary),`Full report: ${Gd(e)}`,""].join(`
|
|
1400
|
-
`)}function tw(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...
|
|
1400
|
+
`)}function tw(n){let e=["# CodeLinter report",""];return n.issues.length===0?e.push("No defects found.",""):e.push(...bk(n.issues),""),e.push("## Summary","",...Pk(n.summary),""),e.join(`
|
|
1401
1401
|
`)}function nw(n){return`${JSON.stringify(n,null,2)}
|
|
1402
|
-
`}function Wd(n){return`Summary: Issues: ${tt(n.issues)} | Errors: ${tt(n.errors)} | Warnings: ${tt(n.warnings)} | Suggestions: ${tt(n.suggestions)} | Files checked: ${tt(n.filesChecked)}`}function
|
|
1403
|
-
`)}function
|
|
1404
|
-
`))}}var lw=new Set([".ets",".c",".cpp"]);function
|
|
1405
|
-
`?(t.push(r),e.push(t),t=[],r="",i+=1):(s==="\r"||(r+=s),i+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function
|
|
1402
|
+
`}function Wd(n){return`Summary: Issues: ${tt(n.issues)} | Errors: ${tt(n.errors)} | Warnings: ${tt(n.warnings)} | Suggestions: ${tt(n.suggestions)} | Files checked: ${tt(n.filesChecked)}`}function vk(n,e){return`Showing ${tt(e)} of ${tt(n)} issues. Use --output-path <path> to write all results.`}function Sk(n){let e=["No","File","Line","Column","Severity","Rule","Message"],t=n.map((r,o)=>({cells:Ik(r,o+1)}));return["CodeLinter report","",Lt(e,t)].join(`
|
|
1403
|
+
`)}function bk(n){let e=["| No | File | Line | Column | Severity | Rule | Message |","| ---: | --- | ---: | ---: | --- | --- | --- |"];for(let[t,r]of n.entries())e.push(Ek(r,t+1));return e}function Ek(n,e){return`| ${[String(e),Gd(An(n.file)),qa(n.line),qa(n.column),An(n.severity),An(n.rule),An(n.message)].map(Ck).join(" | ")} |`}function Pk(n){return[`- Issues: ${tt(n.issues)}`,`- Errors: ${tt(n.errors)}`,`- Warnings: ${tt(n.warnings)}`,`- Suggestions: ${tt(n.suggestions)}`,`- Files checked: ${tt(n.filesChecked)}`]}function Ck(n){return n.replace(Zy,"\\\\").replace(yk,"\\|").replace(wk,"<br>")}function Ik(n,e){return[String(e),Gd(An(Ak(n.file))),qa(n.line),qa(n.column),An(n.severity),An(n.rule),An(n.message)]}function Ak(n){if(!Ei.isAbsolute(n))return n;let e=Ei.relative(process.cwd(),n);return!e||e.startsWith("..")||Ei.isAbsolute(e)?n:e}function Gd(n){return n.replace(Zy,"/")}function An(n){let e=n?.trim();return e||Xy}function qa(n){return n===void 0?Xy:String(n)}function tt(n){return n.toLocaleString("en-US")}var kk=/^-?\d+$/;function qd(){return new Tk("lint").description("Run DevEco Code Linter checks for TS/ArkTS code").addArgument(new Rk("[path]","File or directory to lint").argParser(Mk)).option("--fix","Auto-fix fixable code issues").option("--incremental","Only check uncommitted files").option("--config-path <path>","Path to lint configuration file",Nk).option("--product <product>","Product name defined in build-profile.json5",Lk,"default").option("--format <format>","Report format (choices: default, json)",xk,"default").option("--output-path <path>","Complete report file or directory",Ok).option("--limit <number>","Maximum terminal issues to display when --output-path is omitted",_k).action(async(n,e)=>{await Fk(n,e)})}function xk(n){if(n==="default"||n==="json")return n;throw new Dn("Invalid --format. Expected one of: default, json.")}function Nk(n){Vd(n,"--config-path");let e=je.extname(n).toLowerCase();if(e!==".json"&&e!==".json5")throw new Dn("`--config-path` must point to a .json or .json5 file.");return n}function Lk(n){return rw(n,"product"),n}function Ok(n){return Vd(n,"--output-path"),n}function Mk(n){return Vd(n,"path"),n}function _k(n){if(rw(n,"limit"),!kk.test(n))throw new Dn("`--limit` must be a positive integer.");let e=Number.parseInt(n,10);if(e<=0||!Number.isSafeInteger(e))throw new Dn("`--limit` must be an integer greater than 0.");return e}function rw(n,e){if(n.trim().length===0||sw(n))throw new Dn(`Invalid --${e} value.`)}function Vd(n,e){let t=`\`${e}\``;if(n.length===0||sw(n))throw new Dn(`${t} must be a non-empty path without control characters.`)}async function Fk(n,e){let t=process.cwd(),r=Bk(e.outputPath,e.format,t);e.fix&&console.warn(Dk("Running codelinter with --fix. Ensure your project source is trusted."));let o=await jk(n,e,t);zk(o.diagnostics),process.exitCode=$k(o,r,e.format,e.limit,t)}async function jk(n,e,t){let r=await I.new(),o=new bi(r,t);return Hk(o,{lintPath:n,configPath:e.configPath,product:e.product,fix:e.fix,incremental:e.incremental})}async function Hk(n,e){let t=new dt;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 $k(n,e,t,r,o){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){Uk(e,t,n.report);let i=iw(e,o);process.stdout.write(ew(n.report,i))}else process.stdout.write(Qy(n.report,r));return n.exitCode}catch(i){return console.error(Va("Failed to generate Code Linter report.")),console.error(Va(i.message)),n.exitCode===0?1:n.exitCode}}function Uk(n,e,t){Pi.mkdirSync(je.dirname(n),{recursive:!0});let r=e==="json"?nw(t):tw(t);try{Pi.writeFileSync(n,r,{encoding:"utf-8",flag:"wx"})}catch(o){throw o.code==="EEXIST"?new Error(`Output file already exists: ${n}`,{cause:o}):o}}function Bk(n,e,t){if(!n)return;let r=qk(n,t),o=Gk(n,r),i=o?je.join(r,Vk(e)):r;if(o||Wk(n,e),Pi.existsSync(i))throw new Dn(`Output file already exists: ${iw(i,t)}`);return i}function Wk(n,e){let t=ow(e);if(je.extname(n).toLowerCase()!==t)throw new Dn(`--output-path must use the ${t} extension for --format ${e}.`)}function Gk(n,e){return Pi.existsSync(e)?Pi.statSync(e).isDirectory():n.endsWith("/")||n.endsWith("\\")||je.extname(n)===""}function qk(n,e){return je.resolve(e,n)}function Vk(n){let e=new Date,t=[e.getFullYear(),e.getMonth()+1,e.getDate()].map((i,s)=>String(i).padStart(s===0?4:2,"0")).join(""),r=[e.getHours(),e.getMinutes(),e.getSeconds()].map(i=>String(i).padStart(2,"0")).join(""),o=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${r}-${o}${ow(n)}`}function ow(n){return n==="json"?".json":".md"}function iw(n,e){let t=je.relative(e,n);return t&&!t.startsWith("..")&&!je.isAbsolute(t)?t:n}function zk(n){n&&process.stderr.write(n)}function sw(n){for(let e of n){let t=e.charCodeAt(0);if(t<=31||t===127)return!0}return!1}import{Command as Jk,InvalidArgumentError as dw}from"commander";import*as W from"path";import*as zd from"os";import{readdirSync as Yk,existsSync as za,readFileSync as Kk,unlinkSync as Xk,copyFileSync as uw,writeFileSync as pw}from"fs";import{execa as Zk}from"execa";import{cyan as ge,yellow as fw}from"colorette";import Qk from"ora";var aw=["default","csv","json"];function mw(n){if(aw.includes(n))return n;throw new dw(`--format must be one of: ${aw.join(", ")} (got "${n}")`)}function ex(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new dw(`--limit must be a positive integer (got "${n}")`);return e}function tx(n){return[...n].sort((e,t)=>{let r=cw(e),o=cw(t);return r.apiVersion-o.apiVersion||r.suffix.localeCompare(o.suffix)})}function cw(n){let e=n.match(/\((\d+)\)/),t=e?Number(e[1]):0,r=n.lastIndexOf("_"),o=r>=0?n.slice(r+1):n;return{apiVersion:t,suffix:o}}function hw(n){let t=Yk(n,{withFileTypes:!0}).filter(r=>r.isFile()&&r.name.toLowerCase().endsWith(".json")).map(r=>r.name.slice(0,-5));return tx(t)}function nx(n){let e=process.argv;for(let t=0;t<e.length;t+=1){let r=e[t],o;if(r==="--format"&&t+1<e.length?o=e[t+1]:r.startsWith("--format=")&&(o=r.slice(9)),o!==void 0){let i=mw(o);return i==="default"?"csv":i}}return n}async function rx(n){let e=await I.new(),{apiChangeDir:t}=e.getApiscanPaths();m(ge(`[compat:versions] apiChangeDir: "${t}"`));let r=hw(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(`
|
|
1404
|
+
`))}}var lw=new Set([".ets",".c",".cpp"]);function ox(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 o=n.profile.modules.map(s=>s.name).join(", "),i=r.length>1?"are":"is";throw new Error(`Module ${r.map(s=>`"${s}"`).join(", ")} ${i} not defined in build-profile.json5. Available modules: ${o}.`)}function ix(n){for(let e of n){let t=W.resolve(e);if(!za(t))throw new Error(`File "${e}" does not exist.`);let r=W.extname(t).toLowerCase();if(!lw.has(r)){let o=Array.from(lw).join(", ");throw new Error(`Unsupported file extension "${r}" for "${e}". Supported: ${o}.`)}}}function sx(n){let e=[],t=[];for(let r of n)W.extname(r).toLowerCase()===".ets"?e.push(r):t.push(r);return{arkTs:e,cpp:t}}function ax(n){let e=[],t=[],r="",o=!1,i=0;for(;i<n.length;){let s=n[i];o?{field:r,inQuotes:o,i}=cx(n,i,s,r,o):s==='"'?(o=!0,i+=1):s===","?(t.push(r),r="",i+=1):s===`
|
|
1405
|
+
`?(t.push(r),e.push(t),t=[],r="",i+=1):(s==="\r"||(r+=s),i+=1)}return(r.length>0||t.length>0)&&(t.push(r),e.push(t)),e}function cx(n,e,t,r,o){return t!=='"'?{field:r+t,inQuotes:o,i:e+1}:n[e+1]==='"'?{field:r+'"',inQuotes:o,i:e+2}:{field:r,inQuotes:!1,i:e+1}}function lx(n,e){return e.map(t=>{let r=o=>{let i=n.indexOf(o);return i>=0&&i<t.length?t[i]:""};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 dx(n){let e=Kk(n,"utf8"),t=e.startsWith("\uFEFF")?e.slice(1):e,r=ax(t);if(r.length<2)return[];let[o,...i]=r;return lx(o,i)}function ux(n,e){let t=n.match(/CSV saved to:\s*([^\r\n]+\.csv)/);if(!t)return null;let r=t[1].trim();return W.isAbsolute(r)?r:W.join(e,r)}function px(n,e){let t=new Map;for(let i of n){let s=i.changeType||"(unknown)";t.set(s,(t.get(s)??0)+1)}let r=Array.from(t.entries()).sort((i,s)=>s[1]-i[1]||i[0].localeCompare(s[0])),o=Math.max(5,...r.map(([i])=>i.length));console.log(ge("API change scan summary:")),console.log(` ${"Total".padEnd(o)} ${n.length}`);for(let[i,s]of r)console.log(` ${i.padEnd(o)} ${s}`);e&&console.log(` ${"Report".padEnd(o)} ${e}`)}function fx(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(ge(`Details (showing ${t.length}${r>0?` of ${n.length}`:""}):`));let o=[["Title","title"],["Language","language"],["ChangeId","changeId"],["Changed in","changedInSdk"],["Affected Versions","affectedVersions"],["Code Location","codeLocation"]],i=Math.max(...o.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 o)console.log(` ${c.padEnd(i)} ${s(a[l])}`)}r>0&&console.log(fw(` ... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function mx(n,e){let t=n.slice(0,e),r=n.length-t.length;console.log(),console.log(JSON.stringify({count:n.length,records:t},null,2)),r>0&&console.log(fw(`... and ${r} more. you can re-run with --output-path <dir> to save the full report.`))}function hx(n,e){let t=[];for(let r of e){let o=n.profile.modules.find(i=>i.name===r);if(!o)throw new Error(`Module "${r}" not found in build-profile.json5.`);t.push(W.resolve(n.rootDir,o.srcPath))}return t}function gx(n,e,t,r){if(!r.sourceVersion||!r.targetVersion)throw new Error("source-version and target-version are required.");let o=[n,"--startVersion",r.sourceVersion,"--endVersion",r.targetVersion];if(e.length>0){let{arkTs:i,cpp:s}=sx(e),a=d=>W.resolve(process.cwd(),d),c=i.map(a),l=s.map(a);c.length>0&&o.push("--arkTsFiles",c.join(",")),l.length>0&&o.push("--cppFiles",l.join(","))}else if(r.modules&&r.modules.length>0){let i=hx(t,r.modules);o.push("--modulePaths",i.join(","))}else o.push("--projectPath",t.rootDir);return o.push("--outputPath",zd.tmpdir()),o}async function yx(n,e){let t=W.dirname(e[0]);try{let o=(await Zk(n.nodePath,e,{cwd:t,stdin:"ignore",stdout:"pipe",stderr:"inherit"})).stdout;return process.env.DEVECO_CLI_DEBUG&&(console.log(ge("[compat:check] === scan stdout ===")),process.stdout.write(o),o.endsWith(`
|
|
1406
1406
|
`)||process.stdout.write(`
|
|
1407
1407
|
`),console.log(ge("[compat:check] === end stdout ==="))),o}catch(r){let o=r;process.env.DEVECO_CLI_DEBUG&&o.stdout&&(console.log(ge("[compat:check] === scan stdout (on error) ===")),process.stdout.write(o.stdout),o.stdout.endsWith(`
|
|
1408
1408
|
`)||process.stdout.write(`
|
|
1409
1409
|
`),console.log(ge("[compat:check] === end stdout ===")));let i=new Error(`Compatibility scan failed: ${o.message}`+(o.stderr?`
|
|
1410
|
-
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function
|
|
1411
|
-
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),o=e.indexOf(n.targetVersion);if(r>=o)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
|
|
1412
|
-
`}function Ax(n,e,t,r){r===".csv"?uw(n,t):pw(t,gw(e),"utf8"),m(ge(`[compat:check] saved report: "${t}"`))}function Dx(n,e,t,r){if(r==="json"){let i=W.basename(n,".csv"),s=W.join(t,`${i}.json`);return pw(s,gw(e),"utf8"),m(ge(`[compat:check] saved report: "${s}"`)),s}let o=W.join(t,W.basename(n));return uw(n,o),m(ge(`[compat:check] saved report: "${o}"`)),o}async function Rx(n,e){let t=new xe(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(o){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function Tx(n,e){yx(n,e);let t=G.discover(process.cwd());e.modules&&e.modules.length>0&&rx(t,e.modules),n.length>0&&ox(n);let r=await I.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(ge(`[compat:check] script: "${i}"`));let s=hw(o);wx(e,s),e.outputPath&&m(ge(`[compat:check] outputPath: "${e.outputPath}"`));let a=Cx(e.outputPath,e.format);return m(ge(`[compat:check] outputTarget: ${a.kind}`)),Ix(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function kx(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await Tx(n,e),s=Zk({text:"Running compatibility check...",color:"cyan"}).start();try{await Rx(i,e);let a=hx(r,n,t,e);Sx(r,a);let c=await gx(i,a),l=dx(c,zd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ge(`[compat:check] tmp csv: "${l}"`));let d=lx(l),h=null;if(o.kind==="file")Ax(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=Dx(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);bx(l),s.stop(),vx(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Jd=new zk("compat").description("Compatibility checking utilities.");Jd.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.',mw,"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)",Qk,100).action(async(n,e)=>{await kx(n,e)});Jd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=tx("csv");await nx(n)});var yw=Jd;var ww=new xx("check").description("Run DevEco project checks").addCommand(qd());b()||ww.addCommand(yw);var vw=ww;import{Command as yL}from"commander";import{green as yu,red as wL}from"colorette";import wu from"fs";import nv from"path";import vL from"json5";import{readFileSync as oN}from"fs";import{join as Nx}from"path";var ee={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"},He={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:Nx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ye={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"},mt={FORBIDDEN:403,UNAUTHORIZED:401},E={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."},X={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Ja(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Yd(n){let e=n.replace(He.TEAM_ID_INVALID_CHARS,"");return`${He.CERT_NAME_PREFIX}${e}.cer`}function ro(n,e,t){if(n===mt.FORBIDDEN)return e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===mt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(ye.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(ye.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=Lx(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function Lx(n){let e=Sw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Sw(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Sw(n){try{return JSON.parse(n)}catch{return null}}function Kd(n){return JSON.parse(n)}async function bw(n){let e=`${ee.BASE_URL}${ee.CERT_LIST_PATH}`,t=await x.postAllowFailure(e,{headers:Ja(n)});if(t.statusCode!==200)throw ro(t.statusCode,t.statusText,t.data);return Kd(t.data)?.certList??[]}async function Ya(n,e){return(await bw(n)).find(r=>r.certName===e)??null}async function Xd(n,e){let t=`${ee.BASE_URL}${ee.CERT_DELETE_PATH}`,r=await x.deleteAllowFailure(t,{headers:Ja(n),params:{certIds:[e]}});if(r.statusCode!==200)throw ro(r.statusCode,r.statusText,r.data);return Kd(r.data)?.ret?.code===0}async function Zd(n,e,t){let r=`${ee.BASE_URL}${ee.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:He.CERT_TYPE_DEBUG},i=await x.postAllowFailure(r,{headers:Ja(n),params:o});if(i.statusCode!==200)throw ro(i.statusCode,i.statusText,i.data);if(!i.data.includes(ye.SUCCESS_MARKER))throw ro(void 0,i.statusText,i.data)}async function Qd(n,e){let t=`${ee.BASE_URL}${ee.CERT_DOWNLOAD_URL_PATH}`,r=await x.postAllowFailure(t,{headers:Ja(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw ro(r.statusCode,r.statusText,r.data);return Kd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as Ox,writeFileSync as Mx,existsSync as _x}from"fs";import{dirname as Fx}from"path";async function Ci(n,e){let{statusCode:t,statusText:r,buffer:o}=await x.getBinaryAllowFailure(n,{timeout:He.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===mt.FORBIDDEN&&r===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=Fx(e);_x(i)||Ox(i,{recursive:!0}),Mx(e,o)}import tN from"fs/promises";import{readFileSync as nN}from"fs";import Ka from"path";import Cw from"crypto";import jx from"os";import Ii from"fs/promises";var Iw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Ew=["ECC","RSA"],Pw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],Hx={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},$x=8,eu=64,Ux=/[\\:*?"<>|=-]/g,ht={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Bx(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>eu)throw new Error(`The length of keyAlias cannot exceed ${eu}`);if(!Ew.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Ew.join(" / ")}`);let e=Hx[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Wx(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(!Pw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Pw.join(" / ")}`)}function Gx(n){return Cw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function qx(n){let e=n?.trim()??"";return e&&e.replace(Ux,"_").slice(0,eu)||ht.productName}async function Aw(){let n=await I.new(),e=n.javaPath;if(!e&&!b())throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Ka.join(t,"default","openharmony","toolchains","lib",r);try{await Ii.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function Vx(n){let{javaPath:e,toolPath:t}=await Aw(),r=[Iw.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 o=r.map(i=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function zx(n){let{javaPath:e,toolPath:t}=await Aw(),r=[Iw.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 o=r.map(i=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function Jx(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Bx(n);let e=await Vx(n),t=await wo(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 Yx(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Wx(n);let e=await zx(n),t=await wo(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 Kx(n=$x){return Cw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Xx(){let n=jx.homedir();try{await Ii.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ka.join(n,b()?"Documents":"",".ohos","config");try{await Ii.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 Pe(n,e,t){let r=qx(n),o=Ka.basename(e),i=Gx(e),s=`${r}_${o}_${i}=.${t}`,a=await Xx();return Ka.join(a,s)}function Zx(n){let e;try{e=G.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function Qx(n){try{await Ii.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function eN(n){try{await Ii.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function tu(n,e,t){let r=process.cwd(),o=Zx(r);await Qx(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=Kx(),s=await Pe(n??"",o,"p12"),a=await Pe(n??"",o,"csr");return console.log("Start generating p12"),await Jx({keyAlias:e?.keyAlias??ht.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??ht.keyAlg,keySize:e?.keySize??ht.keySize,keystoreFile:s,keystorePwd:i}),await eN(s),console.log("Start generating csr"),await Yx({subject:t?.subject??ht.csrSubject,outFile:a,keyAlias:t?.keyAlias??ht.keyAlias,keyPwd:i,signAlg:t?.signAlg??ht.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??ht.keyAlias}}var rN=["p12","cer","csr","p7b"];async function nu(n,e){for(let t of rN){let r=await Pe(n,e,t);await tN.rm(r,{force:!0})}}function ru(n){let e;try{e=nN(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!He.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Dw(n,e){return{certPath:await Pe(n,e,"cer"),csrPath:await Pe(n,e,"csr"),p12Path:await Pe(n,e,"p12"),profilePath:await Pe(n,e,"p7b")}}async function ou(n,e){let t=e??"",r=G.discover(process.cwd()).rootDir;await nu(t,r);let o=Yd(n.teamId),i=await Ya(n,o);if(i&&!await Xd(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await tu(e),a;try{a=oN(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await Zd(n,a,o);let c=await Ya(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Qd(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Pe(t,r,"cer");await Ci(l,d),ru(d);let h=await Pe(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import sc from"crypto";import xn from"fs";import*as Bw from"path";import AN from"json5";import{execa as Hw}from"execa";import $w from"node-forge";import{createCipheriv as iN,createDecipheriv as sN,pbkdf2Sync as aN,randomBytes as cu}from"crypto";import{promises as rr}from"fs";import{dirname as cN,join as gt}from"path";var Xa=3,Ai=16,lN=1e4,Rw="material",dN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Nw="aes-128-gcm",nr=12,Za=16,Rn=4;function iu(n){return new Uint8Array(cu(n))}function uN(n){return cu(n).toString("hex")}function pN(...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 o=0;for(let i of n)o^=i[r];t[r]=o}return t}function Tw(n,e,t=lN,r=Ai){let o=[...n,dN],i=pN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=aN(a,e,t,r,"sha256");return new Uint8Array(c)}function kw(n,e){let t=cu(nr),r=iN(Nw,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Rn+nr+s.length);return c.writeUInt32BE(a,0),t.copy(c,Rn),s.copy(c,Rn+nr),c}function xw(n,e){if(e.length<Rn+nr+Za)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Rn,Rn+nr),o=e.subarray(Rn+nr,Rn+nr+t);if(o.length<Za)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Za),s=o.subarray(o.length-Za),a=sN(Nw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function fN(n){try{await rr.rm(n,{recursive:!0,force:!0})}catch{}}async function su(n){let e=await rr.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 rr.readFile(gt(n,t[0]))}async function au(n,e){let t=uN(Ai),r=gt(n,t);return await rr.writeFile(r,e),t}var Tn=class{static async generateMaterial(e){let t=gt(e,Rw);await fN(t);let r=gt(t,"ac"),o=gt(t,"ce");await rr.mkdir(r,{recursive:!0}),await rr.mkdir(o,{recursive:!0});for(let d=0;d<Xa;d++)await rr.mkdir(gt(t,"fd",String(d)),{recursive:!0});let i=iu(Ai),s=[];for(let d=0;d<Xa;d++)s.push(iu(Ai));let a=iu(Ai),c=Tw(s,i),l=kw(c,a);await au(r,i),await au(o,l);for(let d=0;d<Xa;d++){let h=gt(t,"fd",String(d));await au(h,s[d])}return a}static async readMaterial(e){let t=gt(e,Rw),r=gt(t,"ac"),o=new Uint8Array(await su(r)),i=[];for(let d=0;d<Xa;d++){let h=gt(t,"fd",String(d)),w=await su(h);i.push(new Uint8Array(w))}let s=gt(t,"ce"),a=await su(s),c=Tw(i,o),l=xw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=cN(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return kw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return xw(r,o).toString("utf8")}};import Fw from"fs";import oc from"path";import vN from"json5";import*as Qa from"fs";import*as Lw from"path";function ec(n){let e=Lw.resolve(n);if(!Qa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Qa.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 o=r?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as io from"fs";import*as $e from"path";import{debuglog as oo}from"util";var Ow={"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 mN(n){return Object.prototype.hasOwnProperty.call(Ow,n)}function tc(n){if(mN(n))return Ow[n]}var Mw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as hN}from"url";var rc=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 nc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function _w(n){return n==null||n.length===0}function gN(n){return!_w(n)}function lu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function yN(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 wN(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 kn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=$e.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=$e.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,r),i=this.getOrCreateSet(this.aclPermissionInfoMap,r);o.clear(),i.clear();let s=$e.join(t.sdkPath,"default","sdk-pkg.json"),a=ec(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}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=$e.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(io.existsSync(e))return io.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=hN(e);if(t.includes("dist")){let s=$e.dirname(t),a=$e.dirname(s);return $e.join(a,"src","resources")}let r=$e.dirname(t),o=$e.dirname(r),i=$e.dirname(o);return $e.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{oo("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:nc(o)?Object.values(o):[]).filter(nc).map(a=>new rc(a));s.forEach(a=>{let c=a.permissionInsteadName;gN(c)&&(a.permissionInsteadName=tc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){oo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!nc(i))return;let s=i,a=lu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(_w(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||lu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||lu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:yN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new rc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=wN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=$e.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!io.existsSync(t))return;let r;try{r=io.readFileSync(t,"utf-8")}catch(s){oo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!nc(s)){oo("json object is null");return}o=s}catch(s){oo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){oo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=tc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=tc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ic(n,e){let t=new Set,r=new Set;kn.handleSpecificAclPermissions(),kn.initAclPermission(n,e);for(let o of n.profile.modules){let i=jw(o,n,e,r,oc.join("src","main"));for(let a of i)t.add(a);let s=jw(o,n,e,r,oc.join("src","ohosTest"));for(let a of s)t.add(a)}return SN(r),t}function SN(n){if(n.size>0)throw new Error(Mw.DUPLICATE_PERMISSION)}function jw(n,e,t,r,o){let i=EN(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let S=bN(w,"name");S&&s.push(S)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=oc.join(t.sdkPath,"default","sdk-pkg.json"),l=ec(c),d=kn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let S=Number(w.minSupportApiLevel);return Number.isFinite(S)&&S<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function bN(n,e){let t=n[e];return typeof t=="string"?t:""}function EN(n,e,t){let r=oc.join(n,e.srcPath,t,"module.json5"),o=PN(r);if(o==null)return null;let i=CN(o,"module");return i==null?null:IN(i,"requestPermissions")}function PN(n){try{if(!Fw.existsSync(n))return null;let e=Fw.readFileSync(n,"utf-8");return vN.parse(e)}catch{return null}}function CN(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 IN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var uu=class{verifyStorePassword(e,t){try{let r=xn.readFileSync(e),o=$w.asn1.fromDer(r.toString("binary"));return $w.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new sc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new sc.X509Certificate(xn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new sc.X509Certificate(i);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 DN(n){let e=xn.readFileSync(n,"utf-8"),t=RN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:du(o["bundle-name"]),expiryDate:TN(r?.validity?.["not-after"]),cerFingerprintInProfile:kN(du(o["development-certificate"])),deviceUdidsInProfile:xN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:NN(r?.acls?.["allowed-acls"]),teamIdInProfile:du(o["developer-id"])}}function RN(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,o=!1,i=!1;for(let s=e;s<n.length;s++){let a=n[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function TN(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function kN(n){if(!n)return null;try{let t=new sc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function xN(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 NN(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 du(n){return typeof n=="string"?n:null}var Di=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.#o(r)??n.#i(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,o=e.teamId,i=e.productName??"default",s=G.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([LN(i,a),MN(t.hdcPath)]),d=null;if(Uw(c).allExist)try{d=DN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await ON(a,i,c.storeFile),localAclPermissions:[...ic(s,t)].sort(),hapSignTool:new uu,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:qe({force:!0})}):null}static#n(e){let t=Uw(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:qe({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:qe({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(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:qe({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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=FN(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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return jN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:qe({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:qe({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:qe({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:qe({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:qe({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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function LN(n,e){let[t,r,o,i]=await Promise.all([Pe(n,e,"p12"),Pe(n,e,"csr"),Pe(n,e,"cer"),Pe(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function ON(n,e,t){let r=Bw.join(n,"build-profile.json5");if(!xn.existsSync(r))return;let o;try{o=AN.parse(xn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Tn.decryptPassword(a,t)}catch{return}}async function MN(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Hw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1413
|
-
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{m(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await Hw(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=
|
|
1414
|
-
`);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+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 Uw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)xn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function
|
|
1415
|
-
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{let i=await
|
|
1416
|
-
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function WN(n,e){let{stdout:t}=await fu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return GN(t)}function GN(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 or from"fs";import{createHash as qN}from"crypto";import{debuglog as Kt}from"util";import{Buffer as Kw}from"buffer";import{createPublicKey as VN,X509Certificate as mu}from"crypto";import{readFileSync as zN}from"fs";import ir from"node-forge";async function Xw(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${ee.BASE_URL}${ee.PROVISION_ADD_TEST_PATH}`,h=JN(t,r),w=await KN(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Kt("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let S=w.profileInfo,se=(await eL(n,S.provisionFileUrl)).urlList,Ue=w.profileInfo.id;if(se&&se.length>0){let nt=await Dw(t,o),rt=nt.profilePath;if(!await tL(se,rt))throw await Yw(n,Ue),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Yw(n,Ue),or.existsSync(nt.certPath)&&or.existsSync(rt)&&or.existsSync(nt.p12Path)){let fc=or.readFileSync(nt.certPath,"utf8"),mc=or.readFileSync(rt,"utf8");return nL(mc,fc,nt.p12Path,c,l)||QN(rt),rt}}throw new Error(E.ADD_PROFILE_FAIL)}function JN(n,e){let t=n?`${n}_`:"";return`${YN(`${t}${e}_${e}`)}`}function YN(n){return qN("sha256").update(n).digest("hex").substring(0,16)}async function KN(n,e,t,r,o,i,s){XN(r);let a=gu(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await x.postAllowFailure(e,{headers:a,params:c});if(!l)throw Kt("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw hu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Kt(`add provision fail: ${l.data}`),ZN(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:h}}}function hu(n,e,t){return n===mt.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===mt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function XN(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!He.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function ZN(n,e){if(n.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ye.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function Yw(n,e){if(!e||e.trim().length===0)return;let t=`${ee.BASE_URL}${ee.PROVISION_DELETE_PATH}?id=${e}`,r=await x.deleteAllowFailure(t,{headers:gu(n)});if(r.statusCode!==200)throw hu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&Kt(`delete provision failed: ${r.data}`)}function QN(...n){for(let e of n)try{or.existsSync(e)&&or.unlinkSync(e)}catch(t){Kt(`delete local sign file error: ${t.message}`)}}async function eL(n,e){let t=`${ee.BASE_URL}${ee.CERT_DOWNLOAD_URL_PATH}`,r=gu(n),o={sourceUrls:e},i=await x.postAllowFailure(t,{headers:r,params:o});if(!i)throw Kt("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw hu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Kt("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function tL(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Ci(t,e),!0}function nL(n,e,t,r,o){return rL(n,e),r=r||He.TARGET_FRIENDLY_NAME,o=o||"",oL(e,t,r,o),!0}function rL(n,e){if(e.lastIndexOf(He.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(He.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function oL(n,e,t,r){let o=n.matchAll(He.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=iL(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let S=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${S}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!aL(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function iL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new mu(t);let r=Kw.from(t,"base64");return new mu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function sL(n){if(n.cert){let e=ir.pki.publicKeyToPem(n.cert.publicKey);return VN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=ir.asn1.toDer(n.asn1).getBytes(),t=Kw.from(e,"binary");return new mu(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Kt(`Failed to parse cert from asn1: ${e}`),null}return null}function aL(n,e,t,r){try{let o=zN(n),i=ir.asn1.fromDer(ir.util.createBuffer(o)),c=ir.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:ir.pki.oids.certBag})[ir.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=sL(l);if(!h)continue;if(r.some(S=>{let A=S.publicKey.export({type:"spki",format:"der"});return h.equals(A)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return Kt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function gu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Qw="https://developer.huawei.com",cL={"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"},lL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function dL(n){let e=cL[n];return e?`${Qw}${e}`:void 0}function uL(){return`${Qw}${lL}`}var pL={"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 Zw(n,e){return(pL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function fL(n){return Array.from(n).join(", ")}function ev(n,e){if(n.size===0)return;let t=kn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=dL(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;i.add(`${w} (${h.permissionHelpUrlKey})`)}let s=uL(),a=Zw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=Zw("acl.permissions.warn",[fL(o),l,c]);console.log(d)}var cc=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=G.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(X.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:X.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import mL from"fs";import tv from"path";var lc=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(X.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=tv.join(t,"default","openharmony","toolchains","lib",r);if(!mL.existsSync(o)){let i=tv.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var dc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await De.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await De.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(X.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(X.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(X.TEAM_INFO_FAILED);try{if((await sn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(X.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(X.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(X.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(X.REALNAME_REQUIRED)):{passed:!0,message:""}:e(X.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await sn();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.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(o){return m(`[EnvCheck] Team ID check failed: ${o.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(X.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(X.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function hL(n){try{let{teamList:e}=await sn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function gL(n){let e=await De.getUserInfo(),t=await De.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await hL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await ac(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var uc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await gL(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 i=await ne.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(X.DEVICE_MISSING)):i.some(a=>jn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(X.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(X.DEVICE_DETECT_FAILED)}}};var pc=class{projectChecker=new cc;toolchainChecker=null;authChecker=new dc;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=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new lc(e),this.deviceChecker=new uc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(X.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))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 SL(n){if(wu.existsSync(n)){let e=wu.readFileSync(n,"utf-8");return vL.parse(e)}return{app:{signingConfigs:[],products:[]}}}function bL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function EL(n){if(n.keyPwd===n.storePassword){let r=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Tn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function PL(n,e,t){let r=nv.join(n,"build-profile.json5"),o=SL(r);bL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await EL(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ht.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),wu.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function CL(n){let e=await De.getUserInfo(),t=await De.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 IL(n){let e=n.product||"default";await new pc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await CL(n),o=await I.new(),{shouldRegenerate:i}=await Di.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(yu("Signature generation completed successfully."));return}await AL(n,r,o),console.log(yu("Signature generation completed successfully."))}async function AL(n,e,t){let r=await ou(e,n.product),o=DL(n,e,r,t);o.allDeviceIds=await Gw(e,t.hdcPath),await Xw(e,o);let i=G.discover(process.cwd()).rootDir;await PL(i,r,n.product??"default"),console.log(yu(`Signing config written to ${nv.join(i,"build-profile.json5")}`))}function DL(n,e,t,r){let o=process.cwd(),i=G.discover(o),s=ic(i,r);return ev(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var rv=new yL("signature").description("Generate application signature.");rv.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 IL(n)}catch(e){console.error(wL(e.message)),process.exit(1)}});var ov=rv;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";RL();ie.name("devecocli").description("HarmonyOS application development command line tool").version("0.3.0-TD.2.4");ie.addCommand(rp);ie.addCommand(Lp);ie.addCommand(Fp);ie.addCommand(Kp);ie.addCommand(Vf);ie.addCommand(ym);ie.addCommand(bm);ie.addCommand(xm);ie.addCommand(Hm);ie.addCommand(ih);ie.addCommand(gy);ie.addCommand(ov);ie.addCommand(vw);ie.addCommand(Uy);b()||ie.addCommand(Cf);var vu=process.argv.slice(2);vu.length>=2&&vu[vu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var kL=new Set(["update","auth"]);ie.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ie;)t=t.parent;kL.has(t.name())||await I.checkVersion()});ie.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(TL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|
|
1410
|
+
${o.stderr}`:""));throw o.stdout&&(i.stdout=o.stdout),i}}function wx(n,e){if(n.length>0&&e.modules&&e.modules.length>0)throw new Error("Cannot use `--modules` together with file arguments. Use either file-level scanning (with files) or module-level scanning (with --modules).");if(!e.sourceVersion)throw new Error("--source-version is required.");if(!e.targetVersion)throw new Error("--target-version is required.");if(!e.outputPath&&e.format==="csv")throw new Error("--format csv requires --output-path. For console output, use --format json or --format default (or omit the flag).")}function vx(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.
|
|
1411
|
+
Run \`devecocli compat versions\` to see all available versions.`)}if(n.sourceVersion&&n.targetVersion){let r=e.indexOf(n.sourceVersion),o=e.indexOf(n.targetVersion);if(r>=o)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 Sx(n,e,t,r,o){o==="none"&&(t==="json"?mx(n,r):fx(n,r)),px(n,e)}function bx(n,e){let t=W.dirname(n),r=W.basename(n),o=e.slice(1).map(i=>i.startsWith("--")?i:`"${i}"`).join(" ");m(ge(`[compat:check] command: cd "${t}" && node "${r}" ${o}`))}function Ex(n){try{Xk(n),m(ge(`[compat:check] cleaned up tmp report: "${n}"`))}catch(e){m(ge(`[compat:check] failed to clean up tmp report: ${e.message}`))}}var Px=[".csv",".json"];function Cx(n){return Px.includes(n.toLowerCase())}function Ix(n,e){if(!n)return{kind:"none"};let t=W.extname(n).toLowerCase();if(!Cx(t))return{kind:"dir",dirPath:W.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:W.resolve(n),ext:t}}function Ax(n){if(n.kind==="file"){if(za(n.filePath))throw new Error(`Target file "${n.filePath}" already exists. Remove it first, or choose a different --output-path.`);let e=W.dirname(n.filePath);if(!za(e))throw new Error(`Target directory "${e}" does not exist. Create it first, or choose a different --output-path.`)}else if(n.kind==="dir"&&!za(n.dirPath))throw new Error(`Target directory "${n.dirPath}" does not exist. Create it first, or choose a different --output-path.`)}function gw(n){return JSON.stringify({count:n.length,records:n},null,2)+`
|
|
1412
|
+
`}function Dx(n,e,t,r){r===".csv"?uw(n,t):pw(t,gw(e),"utf8"),m(ge(`[compat:check] saved report: "${t}"`))}function Rx(n,e,t,r){if(r==="json"){let i=W.basename(n,".csv"),s=W.join(t,`${i}.json`);return pw(s,gw(e),"utf8"),m(ge(`[compat:check] saved report: "${s}"`)),s}let o=W.join(t,W.basename(n));return uw(n,o),m(ge(`[compat:check] saved report: "${o}"`)),o}async function Tx(n,e){let t=new xe(n,process.cwd(),!0),r=e.modules&&e.modules.length>0?e.modules[0]:void 0;try{await t.compileNative("default",r)}catch(o){throw new Error(`hvigorw compileNative failed (module=${r??"<project>"}): `+o.message,{cause:o})}}async function kx(n,e){wx(n,e);let t=G.discover(process.cwd());e.modules&&e.modules.length>0&&ox(t,e.modules),n.length>0&&ix(n);let r=await I.new(),{apiChangeDir:o,scriptPath:i}=r.getApiscanPaths();m(ge(`[compat:check] script: "${i}"`));let s=hw(o);vx(e,s),e.outputPath&&m(ge(`[compat:check] outputPath: "${e.outputPath}"`));let a=Ix(e.outputPath,e.format);return m(ge(`[compat:check] outputTarget: ${a.kind}`)),Ax(a),{project:t,scriptPath:i,target:a,toolProvider:r}}async function xx(n,e){let{project:t,scriptPath:r,target:o,toolProvider:i}=await kx(n,e),s=Qk({text:"Running compatibility check...",color:"cyan"}).start();try{await Tx(i,e);let a=gx(r,n,t,e);bx(r,a);let c=await yx(i,a),l=ux(c,zd.tmpdir());if(!l)throw new Error("Scanner output format unexpected: missing report path.");m(ge(`[compat:check] tmp csv: "${l}"`));let d=dx(l),h=null;if(o.kind==="file")Dx(l,d,o.filePath,o.ext),h=o.filePath;else if(o.kind==="dir")h=Rx(l,d,o.dirPath,e.format);else if(o.kind!=="none")throw new Error(`Unexpected output target kind: ${o.kind}`);Ex(l),s.stop(),Sx(d,h,e.format,e.limit,o.kind)}catch(a){throw s.fail("Compatibility check failed"),a}}var Jd=new Jk("compat").description("Compatibility checking utilities.");Jd.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.',mw,"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)",ex,100).action(async(n,e)=>{await xx(n,e)});Jd.command("versions").description("List all available target SDK versions for compatibility checking").action(async()=>{let n=nx("csv");await rx(n)});var yw=Jd;var ww=new Nx("check").description("Run DevEco project checks").addCommand(qd());b()||ww.addCommand(yw);var vw=ww;import{Command as wL}from"commander";import{green as yu,red as vL}from"colorette";import wu from"fs";import nv from"path";import SL from"json5";import{readFileSync as iN}from"fs";import{join as Lx}from"path";var ee={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"},He={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:Lx(".ohos","config"),DOWNLOAD_CONNECT_TIMEOUT_MS:5e3},ye={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"},mt={FORBIDDEN:403,UNAUTHORIZED:401},E={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."},X={TOOLCHAIN_INIT_FAILED:"Auto-sign failed: unable to initialize toolchain",LOGIN_REQUIRED:"Failed to automatically generate signatures.Run devecocli auth login to sign in.",TEAM_INFO_FAILED:"Failed to obtain user team information.Check the network connection, HTTP proxy, and other configurations.",REALNAME_REQUIRED:"Users without real-name verification are not supported.Complete real-name verification in AppGallery Connect.",SESSION_EXPIRED:"User session expired or token invalid. Please login again.",REGION_CHINA_ONLY:"This feature is only available for accounts registered in Chinese mainland.",DEVICE_MISSING:"Unable to create the profile file due to missing devices.Connect a device through IP or USB, or manually add a device in AppGallery Connect first.If you are installing the HAP package on an emulator, you can skip the signing step.",DEVICE_DETECT_FAILED:"Unable to detect devices. Please check hdc status. If installing HAP on an emulator, signature step can be skipped.",JAVA_PLATFORM_UNSUPPORTED:"Java environment not found (Windows/macOS/Linux only).",JAVA_REQUIRED:"Java runtime is required to run hvigor.Set JAVA_HOME or add Java to PATH.",PROJECT_DIR_MISSING:"Not in a valid project directory (project-level build-profile.json5 not found).",ATOMIC_SERVICE_UNSUPPORTED:"AtomicService projects are not yet supported. Please configure signing manually."};function Ja(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}function Yd(n){let e=n.replace(He.TEAM_ID_INVALID_CHARS,"");return`${He.CERT_NAME_PREFIX}${e}.cer`}function ro(n,e,t){if(n===mt.FORBIDDEN)return e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN);if(n===mt.UNAUTHORIZED)return new Error(E.ERR_UNAUTHORIZED);if(t.includes(ye.USER_NOT_HARMONY_CODE))return new Error(E.ERR_USER_NOT_HARMONY);if(t.includes(ye.CERT_LIMIT_CODE))return new Error(E.ERR_CERT_LIMIT_REACHED);let r=Ox(t);return new Error(r??E.ERR_DOWNLOAD_CER)}function Ox(n){let e=Sw(n);if(!e||typeof e!="object")return null;let t=e.ret;if(t==null)return null;let r=typeof t=="string"?Sw(t):t;if(r&&typeof r=="object"){let o=r.msg;if(typeof o=="string"&&o.trim()!=="")return o}return null}function Sw(n){try{return JSON.parse(n)}catch{return null}}function Kd(n){return JSON.parse(n)}async function bw(n){let e=`${ee.BASE_URL}${ee.CERT_LIST_PATH}`,t=await x.postAllowFailure(e,{headers:Ja(n)});if(t.statusCode!==200)throw ro(t.statusCode,t.statusText,t.data);return Kd(t.data)?.certList??[]}async function Ya(n,e){return(await bw(n)).find(r=>r.certName===e)??null}async function Xd(n,e){let t=`${ee.BASE_URL}${ee.CERT_DELETE_PATH}`,r=await x.deleteAllowFailure(t,{headers:Ja(n),params:{certIds:[e]}});if(r.statusCode!==200)throw ro(r.statusCode,r.statusText,r.data);return Kd(r.data)?.ret?.code===0}async function Zd(n,e,t){let r=`${ee.BASE_URL}${ee.CERT_ADD_PATH}`,o={csr:e,certName:t,certType:He.CERT_TYPE_DEBUG},i=await x.postAllowFailure(r,{headers:Ja(n),params:o});if(i.statusCode!==200)throw ro(i.statusCode,i.statusText,i.data);if(!i.data.includes(ye.SUCCESS_MARKER))throw ro(void 0,i.statusText,i.data)}async function Qd(n,e){let t=`${ee.BASE_URL}${ee.CERT_DOWNLOAD_URL_PATH}`,r=await x.postAllowFailure(t,{headers:Ja(n),params:{sourceUrls:e}});if(r.statusCode!==200)throw ro(r.statusCode,r.statusText,r.data);return Kd(r.data)?.urlsInfo?.[0]?.newUrl??null}import{mkdirSync as Mx,writeFileSync as _x,existsSync as Fx}from"fs";import{dirname as jx}from"path";async function Ci(n,e){let{statusCode:t,statusText:r,buffer:o}=await x.getBinaryAllowFailure(n,{timeout:He.DOWNLOAD_CONNECT_TIMEOUT_MS});if(t!==200)throw t===mt.FORBIDDEN&&r===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_DOWNLOAD_CER);let i=jx(e);Fx(i)||Mx(i,{recursive:!0}),_x(e,o)}import nN from"fs/promises";import{readFileSync as rN}from"fs";import Ka from"path";import Cw from"crypto";import Hx from"os";import Ii from"fs/promises";var Iw={GENERATE_KEYPAIR:"generate-keypair",GENERATE_CSR:"generate-csr"},Ew=["ECC","RSA"],Pw=["SHA256withECDSA","SHA384withECDSA","SHA256withRSA","SHA384withRSA"],$x={ECC:["NIST-P-256","NIST-P-384"],RSA:["2048","3072","4096"]},Ux=8,eu=64,Bx=/[\\:*?"<>|=-]/g,ht={productName:"default",keyAlias:"debugKey",keyAlg:"ECC",keySize:"NIST-P-256",csrSubject:"CN=DebugKey",signAlg:"SHA256withECDSA"};function Wx(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>eu)throw new Error(`The length of keyAlias cannot exceed ${eu}`);if(!Ew.includes(n.keyAlg))throw new Error(`Invalid key algorithm ${n.keyAlg}, available: ${Ew.join(" / ")}`);let e=$x[n.keyAlg];if(!e.includes(n.keySize))throw new Error(`Key algorithm ${n.keyAlg} does not support size ${n.keySize}, available: ${e.join(", ")}`)}function Gx(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(!Pw.includes(n.signAlg))throw new Error(`Invalid sign algorithm ${n.signAlg}, available: ${Pw.join(" / ")}`)}function qx(n){return Cw.createHash("sha256").update(n,"utf8").digest().toString("base64url").replaceAll(/[-_=]/g,"")}function Vx(n){let e=n?.trim()??"";return e&&e.replace(Bx,"_").slice(0,eu)||ht.productName}async function Aw(){let n=await I.new(),e=n.javaPath;if(!e&&!b())throw new Error("Java runtime not found. DevEco Studio JBR is required to run hap-sign-tool.jar.");let t=n.sdkPath;f.info(`\u8BFB\u53D6SDK\u6839\u76EE\u5F55\uFF1A${t}`);let r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=Ka.join(t,"default","openharmony","toolchains","lib",r);try{await Ii.access(o)}catch(i){throw new Error(`${r} not found: ${o}`,{cause:i})}return{javaPath:e,toolPath:o}}async function zx(n){let{javaPath:e,toolPath:t}=await Aw(),r=[Iw.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 o=r.map(i=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-keypair \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function Jx(n){let{javaPath:e,toolPath:t}=await Aw(),r=[Iw.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 o=r.map(i=>["-keyPwd","-keystorePwd"].includes(i)?`${i} ******`:i);return f.debug("generate-csr \u547D\u4EE4\uFF08\u8131\u654F\uFF09\uFF1A",o.join(" ")),b()?[t,...r]:[e,"-jar",t,...r]}async function Yx(n){f.info("\u5F00\u59CB\u751F\u6210 P12 \u5BC6\u94A5\u5E93"),Wx(n);let e=await zx(n),t=await wo(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 Kx(n){f.info("\u5F00\u59CB\u751F\u6210 CSR \u8BC1\u4E66\u8BF7\u6C42"),Gx(n);let e=await Jx(n),t=await wo(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 Xx(n=Ux){return Cw.randomBytes(n).toString("base64url").replaceAll(/[-_=]/g,"")}async function Zx(){let n=Hx.homedir();try{await Ii.access(n)}catch(t){throw new Error("Invalid user path;",{cause:t})}let e=Ka.join(n,b()?"Documents":"",".ohos","config");try{await Ii.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 Pe(n,e,t){let r=Vx(n),o=Ka.basename(e),i=qx(e),s=`${r}_${o}_${i}=.${t}`,a=await Zx();return Ka.join(a,s)}function Qx(n){let e;try{e=G.discover(n).rootDir}catch(t){throw new Error(`Current directory ${n} is not a valid project root`,{cause:t})}return e}async function eN(n){try{await Ii.access(n)}catch(e){throw new Error(`Project directory ${n} is not accessible, missing read/write permissions`,{cause:e})}}async function tN(n){try{await Ii.access(n)}catch(e){throw new Error(`P12 file ${n} does not exist, terminating CSR generation.`,{cause:e})}}async function tu(n,e,t){let r=process.cwd(),o=Qx(r);await eN(o),f.info(`\u8BC6\u522B\u9879\u76EE\u6839\u76EE\u5F55\uFF1A${o}`);let i=Xx(),s=await Pe(n??"",o,"p12"),a=await Pe(n??"",o,"csr");return console.log("Start generating p12"),await Yx({keyAlias:e?.keyAlias??ht.keyAlias,keyPwd:i,keyAlg:e?.keyAlg??ht.keyAlg,keySize:e?.keySize??ht.keySize,keystoreFile:s,keystorePwd:i}),await tN(s),console.log("Start generating csr"),await Kx({subject:t?.subject??ht.csrSubject,outFile:a,keyAlias:t?.keyAlias??ht.keyAlias,keyPwd:i,signAlg:t?.signAlg??ht.signAlg,keystoreFile:s,keystorePwd:i}),{p12FilePath:s,csrFilePath:a,keyPwd:i,keyAlias:e?.keyAlias??ht.keyAlias}}var oN=["p12","cer","csr","p7b"];async function nu(n,e){for(let t of oN){let r=await Pe(n,e,t);await nN.rm(r,{force:!0})}}function ru(n){let e;try{e=rN(n,"utf-8")}catch{throw new Error(E.ERR_CERT_INVALIDATE)}if(!He.CERT_PATTERN.test(e))throw new Error(E.ERR_CERT_INVALIDATE)}async function Dw(n,e){return{certPath:await Pe(n,e,"cer"),csrPath:await Pe(n,e,"csr"),p12Path:await Pe(n,e,"p12"),profilePath:await Pe(n,e,"p7b")}}async function ou(n,e){let t=e??"",r=G.discover(process.cwd()).rootDir;await nu(t,r);let o=Yd(n.teamId),i=await Ya(n,o);if(i&&!await Xd(n,i.id))throw new Error(E.ERR_DOWNLOAD_CER);let s=await tu(e),a;try{a=iN(s.csrFilePath,"utf-8")}catch{throw new Error(E.ERR_READ_CSR)}console.log("Start generating certificate"),await Zd(n,a,o);let c=await Ya(n,o);if(!c)throw new Error(E.ERR_DOWNLOAD_CER);let l=await Qd(n,c.certObjectId);if(!l)throw new Error(E.ERR_DOWNLOAD_CER);let d=await Pe(t,r,"cer");await Ci(l,d),ru(d);let h=await Pe(t,r,"p7b");return{p12FilePath:s.p12FilePath,csrFilePath:s.csrFilePath,cerFilePath:d,profileFilePath:h,certId:c.id,keyAlias:s.keyAlias,keyPwd:s.keyPwd,storePassword:s.keyPwd}}import sc from"crypto";import xn from"fs";import*as Bw from"path";import DN from"json5";import{execa as Hw}from"execa";import $w from"node-forge";import{createCipheriv as sN,createDecipheriv as aN,pbkdf2Sync as cN,randomBytes as cu}from"crypto";import{promises as rr}from"fs";import{dirname as lN,join as gt}from"path";var Xa=3,Ai=16,dN=1e4,Rw="material",uN=new Uint8Array([49,243,9,115,214,175,91,184,211,190,177,88,101,131,192,119]),Nw="aes-128-gcm",nr=12,Za=16,Rn=4;function iu(n){return new Uint8Array(cu(n))}function pN(n){return cu(n).toString("hex")}function fN(...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 o=0;for(let i of n)o^=i[r];t[r]=o}return t}function Tw(n,e,t=dN,r=Ai){let o=[...n,uN],i=fN(...o),s=Buffer.from(i).toString("utf8"),a=Buffer.from(s,"utf8"),c=cN(a,e,t,r,"sha256");return new Uint8Array(c)}function kw(n,e){let t=cu(nr),r=sN(Nw,n,t),o=Buffer.concat([r.update(e),r.final()]),i=r.getAuthTag(),s=Buffer.concat([o,i]),a=s.length,c=Buffer.alloc(Rn+nr+s.length);return c.writeUInt32BE(a,0),t.copy(c,Rn),s.copy(c,Rn+nr),c}function xw(n,e){if(e.length<Rn+nr+Za)throw new Error("Ciphertext too short");let t=e.readUInt32BE(0),r=e.subarray(Rn,Rn+nr),o=e.subarray(Rn+nr,Rn+nr+t);if(o.length<Za)throw new Error("Ciphertext too short for auth tag");let i=o.subarray(0,o.length-Za),s=o.subarray(o.length-Za),a=aN(Nw,n,r);return a.setAuthTag(s),Buffer.concat([a.update(i),a.final()])}async function mN(n){try{await rr.rm(n,{recursive:!0,force:!0})}catch{}}async function su(n){let e=await rr.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 rr.readFile(gt(n,t[0]))}async function au(n,e){let t=pN(Ai),r=gt(n,t);return await rr.writeFile(r,e),t}var Tn=class{static async generateMaterial(e){let t=gt(e,Rw);await mN(t);let r=gt(t,"ac"),o=gt(t,"ce");await rr.mkdir(r,{recursive:!0}),await rr.mkdir(o,{recursive:!0});for(let d=0;d<Xa;d++)await rr.mkdir(gt(t,"fd",String(d)),{recursive:!0});let i=iu(Ai),s=[];for(let d=0;d<Xa;d++)s.push(iu(Ai));let a=iu(Ai),c=Tw(s,i),l=kw(c,a);await au(r,i),await au(o,l);for(let d=0;d<Xa;d++){let h=gt(t,"fd",String(d));await au(h,s[d])}return a}static async readMaterial(e){let t=gt(e,Rw),r=gt(t,"ac"),o=new Uint8Array(await su(r)),i=[];for(let d=0;d<Xa;d++){let h=gt(t,"fd",String(d)),w=await su(h);i.push(new Uint8Array(w))}let s=gt(t,"ce"),a=await su(s),c=Tw(i,o),l=xw(c,a);return new Uint8Array(l)}static async getStoreKey(e){let t=lN(e);try{return await this.readMaterial(t)}catch{return await this.generateMaterial(t)}}static async encryptedPassword(e,t){let r=await this.getStoreKey(t),o=Buffer.from(e,"utf8");return kw(r,o).toString("hex")}static async decryptPassword(e,t){if(!e)return"";let r=await this.getStoreKey(t),o=Buffer.from(e,"hex");return xw(r,o).toString("utf8")}};import Fw from"fs";import oc from"path";import SN from"json5";import*as Qa from"fs";import*as Lw from"path";function ec(n){let e=Lw.resolve(n);if(!Qa.existsSync(e))throw new Error(`SDK info file not found: ${e}`);let t;try{t=Qa.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 o=r?.data?.apiVersion;if(o==null||o==="")throw new Error(`Missing data.apiVersion in SDK info file: ${e}`);let i=Number(o);if(!Number.isFinite(i))throw new Error(`Invalid data.apiVersion in SDK info file: ${String(o)}`);return i}import*as io from"fs";import*as $e from"path";import{debuglog as oo}from"util";var Ow={"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 hN(n){return Object.prototype.hasOwnProperty.call(Ow,n)}function tc(n){if(hN(n))return Ow[n]}var Mw={DUPLICATE_PERMISSION:"Duplicate permissions detected. Make sure each permission is unique in the same module and try again."};import{fileURLToPath as gN}from"url";var rc=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 nc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function _w(n){return n==null||n.length===0}function yN(n){return!_w(n)}function lu(n,e){let t=n[e];return typeof t=="string"?t:t==null?"":String(t)}function wN(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 vN(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 kn=class{static MIN_API_TO_FIND_ACL_IN_SDK=23;static ACL_PREFIX="ohos.permission.";static ACL_PERMISSIONS_CONFIG_PATH=$e.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=$e.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,o=this.getOrCreateSet(this.aclPermissionNamesMap,r),i=this.getOrCreateSet(this.aclPermissionInfoMap,r);o.clear(),i.clear();let s=$e.join(t.sdkPath,"default","sdk-pkg.json"),a=ec(s);this.MIN_API_TO_FIND_ACL_IN_SDK-a>0?this.initAclPermissionFromBuiltInConfig(o,i):this.initAclPermissionFromSDK(t,o,i)}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=$e.join(this.getResourcesDir(),this.ACL_PERMISSIONS_CONFIG_PATH);if(io.existsSync(e))return io.readFileSync(e,"utf-8")}static getResourcesDir(){let e=import.meta.url,t=gN(e);if(t.includes("dist")){let s=$e.dirname(t),a=$e.dirname(s);return $e.join(a,"src","resources")}let r=$e.dirname(t),o=$e.dirname(r),i=$e.dirname(o);return $e.join(i,"src","resources")}static initAclPermissionFromBuiltInConfig(e,t){let r;try{r=this.readBuiltInConfigText()}catch{oo("read builtin acl permission failed.");return}if(r!==void 0)try{let o=JSON.parse(r),s=(Array.isArray(o)?o:nc(o)?Object.values(o):[]).filter(nc).map(a=>new rc(a));s.forEach(a=>{let c=a.permissionInsteadName;yN(c)&&(a.permissionInsteadName=tc(c)),e.add(a.permissionName)}),s.forEach(a=>{t.add(a)})}catch(o){oo(`failed to parse aclPermissionsInfo.json: ${o}`)}}static initAclPermissionFromSDK(e,t,r){let o=this.parsePermissionDefinitionFile(e);o&&o.forEach(i=>{if(!nc(i))return;let s=i,a=lu(s,this.ACL_NAME_KEY);this.isAclPermission(s,a)&&(_w(a)||(this.generateAclInfos(r,a,s),t.add(a)))})}static isAclPermission(e,t){return this.aclWhiteList.has(t)?!0:this.aclBlackList.has(t)||lu(e,this.ACL_AVAILABLE_LEVEL_KEY)!==this.ACL_AVAILABLE_LEVEL_VALUE||lu(e,this.ACL_AVAILABLE_TYPE_KEY)!==this.ACL_AVAILABLE_TYPE_VALUE?!1:wN(e,this.ACL_PROVISION_ENABLE_KEY)}static generateAclInfos(e,t,r){let o=new rc;o.permissionName=t;let i=t.startsWith(this.ACL_PREFIX)?t.slice(this.ACL_PREFIX.length):t;o.permissionDisplayName=i;let s=vN(r,this.ACL_SINCE_KEY);o.minSupportApiLevel=String(s),this.handleInsteadName(o,i),e.add(o)}static parsePermissionDefinitionFile(e){let t=$e.join(e.sdkPath,"default","openharmony","toolchains",this.PERMISSION_DEFINITIONS_RELATIVE_PATH);if(!io.existsSync(t))return;let r;try{r=io.readFileSync(t,"utf-8")}catch(s){oo(`failed to load permissionDefinitions.json: ${s}`);return}let o;try{let s=JSON.parse(r);if(!nc(s)){oo("json object is null");return}o=s}catch(s){oo(`failed to parse permissionDefinitions.json: ${s}`);return}let i=o[this.ACL_DEFINE_PERMISSION_KEY];if(!Array.isArray(i)){oo("definePermissions is not an array");return}return i}static handleInsteadName(e,t){this.ACL_HAVE_INSTEAD_NAME.has(e.permissionName)&&(e.permissionInsteadName=tc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_INSTEAD_NAME_SUFFIX}`),e.permissionHelpUrlKey=tc(`${this.ACL_CONFIG_PREFIX}${t}${this.ACL_HELP_URL_KEY_SUFFIX}`))}};function ic(n,e){let t=new Set,r=new Set;kn.handleSpecificAclPermissions(),kn.initAclPermission(n,e);for(let o of n.profile.modules){let i=jw(o,n,e,r,oc.join("src","main"));for(let a of i)t.add(a);let s=jw(o,n,e,r,oc.join("src","ohosTest"));for(let a of s)t.add(a)}return bN(r),t}function bN(n){if(n.size>0)throw new Error(Mw.DUPLICATE_PERMISSION)}function jw(n,e,t,r,o){let i=PN(e.rootDir,n,o);if(i==null)return new Set;let s=[];for(let w of i){if(typeof w!="object"||w===null)continue;let S=EN(w,"name");S&&s.push(S)}let a=new Set(s);a.size!==s.length&&r.add(n.name);let c=oc.join(t.sdkPath,"default","sdk-pkg.json"),l=ec(c),d=kn.getAclPermissionInfos(e),h=new Set(Array.from(d).filter(w=>{let S=Number(w.minSupportApiLevel);return Number.isFinite(S)&&S<=l}).map(w=>w.permissionName));for(let w of Array.from(a))h.has(w)||a.delete(w);return a}function EN(n,e){let t=n[e];return typeof t=="string"?t:""}function PN(n,e,t){let r=oc.join(n,e.srcPath,t,"module.json5"),o=CN(r);if(o==null)return null;let i=IN(o,"module");return i==null?null:AN(i,"requestPermissions")}function CN(n){try{if(!Fw.existsSync(n))return null;let e=Fw.readFileSync(n,"utf-8");return SN.parse(e)}catch{return null}}function IN(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 AN(n,e){if(n==null||typeof n!="object")return null;let t=n[e];return Array.isArray(t)?t:null}var uu=class{verifyStorePassword(e,t){try{let r=xn.readFileSync(e),o=$w.asn1.fromDer(r.toString("binary"));return $w.pkcs12.pkcs12FromAsn1(o,t),!0}catch{return!1}}getLocalCerFingerprints(e){let r=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);if(r&&r.length>0)return r.map(o=>this.formatFp(new sc.X509Certificate(o).fingerprint256));try{return[this.formatFp(new sc.X509Certificate(xn.readFileSync(e)).fingerprint256)]}catch{return[]}}getLocalCerExpiry(e,t){if(!t)return null;let o=xn.readFileSync(e,"utf-8").match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g)??[];for(let i of o)try{let s=new sc.X509Certificate(i);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 RN(n){let e=xn.readFileSync(n,"utf-8"),t=TN(e),r=null;if(t)try{r=JSON.parse(t)}catch{r=null}let o=r?.["bundle-info"]??{};return{rawContent:e,bundleNameInProfile:du(o["bundle-name"]),expiryDate:kN(r?.validity?.["not-after"]),cerFingerprintInProfile:xN(du(o["development-certificate"])),deviceUdidsInProfile:NN(r?.["debug-info"]?.["device-ids"]),aclPermissionsInProfile:LN(r?.acls?.["allowed-acls"]),teamIdInProfile:du(o["developer-id"])}}function TN(n){let e=n.indexOf("{");if(e<0)return null;let t=0,r=-1,o=!1,i=!1;for(let s=e;s<n.length;s++){let a=n[s];if(o){i?i=!1:a==="\\"?i=!0:a==='"'&&(o=!1);continue}if(a==='"')o=!0;else if(a==="{")t++;else if(a==="}"&&(t--,t===0)){r=s;break}}return r<0?null:n.slice(e,r+1)}function kN(n){if(typeof n!="number"||!Number.isFinite(n))return null;let e=new Date(n*1e3);return isNaN(e.getTime())?null:e}function xN(n){if(!n)return null;try{let t=new sc.X509Certificate(n).fingerprint256.replace(/:/g,"");return t.match(/.{2}/g)?.join(":")??t}catch{return null}}function NN(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 LN(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 du(n){return typeof n=="string"?n:null}var Di=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.#o(r)??n.#i(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,o=e.teamId,i=e.productName??"default",s=G.discover(process.cwd()),a=s.rootDir,[c,l]=await Promise.all([ON(i,a),_N(t.hdcPath)]),d=null;if(Uw(c).allExist)try{d=RN(c.profileFile)}catch{}return{force:r,teamId:o,productName:i,projectPath:a,materialPaths:c,bundleName:s.getBundleName(),deviceUdids:l,storePassword:await MN(a,i,c.storeFile),localAclPermissions:[...ic(s,t)].sort(),hapSignTool:new uu,profileInfo:d}}static#t(e){return e.force?(m("[reGenerateSign] --force flag set, skipping all checks"),{shouldRegenerate:!0,reason:"--force flag set",checkDetails:qe({force:!0})}):null}static#n(e){let t=Uw(e.materialPaths);return t.allExist?null:(m(`[reGenerateSign] missing files: ${t.missing.join(",")}`),{shouldRegenerate:!0,reason:`Missing files: ${t.missing.join(", ")}`,checkDetails:qe({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:qe({allFilesExist:!0,profileContentNotEmpty:!1})})}static#o(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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!1})})}static#i(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:qe({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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!1})})}static#a(e){let t=jN(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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!1,missingDeviceUdids:t.missing})})}static#c(e){return HN(e.localAclPermissions,e.profileInfo?.aclPermissionsInProfile??[])?null:(m("[reGenerateSign] ACL permissions mismatch"),{shouldRegenerate:!0,reason:"ACL permissions mismatch between project and profile",checkDetails:qe({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:qe({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:qe({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:qe({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:qe({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:qe({allFilesExist:!0,profileContentNotEmpty:!0,profileNotExpired:!0,bundleNameMatched:!0,teamIdMatched:!0,allDevicesInProfile:!0,aclMatched:!0,cerMatched:!0,cerNotExpired:!0,storePasswordValid:!0})}}};async function ON(n,e){let[t,r,o,i]=await Promise.all([Pe(n,e,"p12"),Pe(n,e,"csr"),Pe(n,e,"cer"),Pe(n,e,"p7b")]);return{storeFile:t,csrFile:r,cerFile:o,profileFile:i}}async function MN(n,e,t){let r=Bw.join(n,"build-profile.json5");if(!xn.existsSync(r))return;let o;try{o=DN.parse(xn.readFileSync(r,"utf-8"))}catch{return}let a=(o?.app?.signingConfigs??[]).find(c=>c.name===e)?.material?.storePassword;if(a)try{return await Tn.decryptPassword(a,t)}catch{return}}async function _N(n){m(`Executing: ${n} list targets`);let{stdout:e}=await Hw(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1413
|
+
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{m(`Executing: ${n} -t ${o} shell bm get -u`);let{stdout:i}=await Hw(n,["-t",o,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),s=FN(i);s&&r.push(s)}catch{m(`[reGenerateSign] Failed to get UDID for ${o}, skipping`)}return r}function FN(n){let e=n.trim();if(!e)return null;let t=e.split(`
|
|
1414
|
+
`);for(let o=0;o<t.length-1;o++)if(t[o].includes("udid of current device is")){let s=t[o+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 Uw(n){let e=[n.storeFile,n.csrFile,n.cerFile,n.profileFile],t=[];for(let r of e)xn.existsSync(r)||t.push(r);return{allExist:t.length===0,missing:t}}function jN(n,e){let t=[];for(let r of e)n.includes(r)||t.push(r);return{allPresent:t.length===0,missing:t}}function HN(n,e){let t=[...n].sort(),r=[...e].sort();return t.length!==r.length?!1:t.every((o,i)=>o===r[i])}function qe(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 pu}from"util";import{execa as fu}from"execa";async function Gw(n,e){let t=await ac(n);if(!t)throw new Error(E.DEVICE_LIST_EMPTY);let r=await BN(e);if(t.length===0)for(let s of r)await $N(n,s.udid,s.deviceName);else for(let s of r)await UN(n,t,s.udid,s.deviceName);let i=(await ac(n)).map(s=>s.id);if(i.length===0)throw new Error(E.DEVICE_LIST_EMPTY);return i}async function $N(n,e,t){await zw(n,e,qw(t))}async function UN(n,e,t,r){for(let o=0;o<e.length;o++){if(t===e[o].udid)return;if(o===e.length-1){await zw(n,t,qw(r));return}}}function qw(n){switch(n){case"liteWearable":return"1";case"wearable":return"2";case"tv":return"3";default:return"4"}}async function Ww(n,e=1,t=100){let r=`${ee.BASE_URL}${ee.DEVICE_LIST_PATH}?encodeFlag=0&start=${e}&pageSize=${t}`,o=Jw(n),i=await x.get(r,{headers:o});if(!i)throw pu("query devices failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(i.statusCode!==200)throw Vw(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.list)throw pu("query devices failed: response list is null"),new Error(s.ret?.msg||E.ERROR_WHILE_ADD_DEVICE);return{deviceList:s.list,total:s.totalCount||0}}function Vw(n,e,t){return n===mt.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===mt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):new Error(E.ERROR_WHILE_ADD_DEVICE)}async function ac(n){let t=await Ww(n,1,100);if(!t||!t.deviceList||t.deviceList.length===0)return[];let r=[...t.deviceList],o=t.total,i=Math.floor(o/100)+(o%100===0?0:1);for(let s=2;s<=i;s++){let a=await Ww(n,s,100);if(!a||!a.deviceList||a.deviceList.length===0)break;r.push(...a.deviceList)}return r}async function zw(n,e,t){let r=`${ee.BASE_URL}${ee.DEVICE_ADD_PATH}`,o=Jw(n),s={deviceName:`auto_sign_device_No.${Math.floor(Math.random()*3e3)}${Date.now()}`,udid:e,deviceType:t},a=await x.postAllowFailure(r,{headers:o,params:s});if(!a)throw pu("add device failed: response is null"),new Error(E.ERROR_WHILE_ADD_DEVICE);if(a.statusCode!==200)throw Vw(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(ye.DEVICE_EXCEEDS_LIMIT_CODE)?new Error(E.DEVICE_LIMIT_REACHED):c.includes(ye.DEVICE_NAME_REPEAT_CODE)?new Error(E.DEVICE_NAME_REPEAT):new Error(E.ERROR_WHILE_ADD_DEVICE)}function Jw(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}async function BN(n){let{stdout:e}=await fu(n,["list","targets"],{stdio:["ignore","pipe","pipe"]}),t=[];for(let o of e.split(`
|
|
1415
|
+
`)){let i=o.trim();if(!i||i.startsWith("[Empty]"))continue;let s=i.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 o of t)try{let i=await WN(o,n),s=await GN(o,n);i.length>0&&r.push({id:"",udid:i,deviceName:s})}catch{m(`Failed to get device info for ${o}, skipping`)}return r}async function WN(n,e){let{stdout:t}=await fu(e,["-t",n,"shell","bm","get","-u"],{stdio:["ignore","pipe","pipe"]}),r=t.trim();if(!r)return"";let o=r.split(`
|
|
1416
|
+
`);for(let s=0;s<o.length-1;s++)if(o[s].includes("udid of current device is")){let c=o[s+1].trim().match(/^[A-Fa-f0-9]{64}$/);if(c)return c[0].toUpperCase()}let i=r.match(/[A-Fa-f0-9]{64}/);return i?i[0].toUpperCase():""}async function GN(n,e){let{stdout:t}=await fu(e,["-c","-t",n,"shell","getprop","hw_sc.build.os.deviceType"],{stdio:["ignore","pipe","pipe"]});return qN(t)}function qN(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 or from"fs";import{createHash as VN}from"crypto";import{debuglog as Kt}from"util";import{Buffer as Kw}from"buffer";import{createPublicKey as zN,X509Certificate as mu}from"crypto";import{readFileSync as JN}from"fs";import ir from"node-forge";async function Xw(n,e){console.log("Start generating profile");let{productName:t,bundleName:r,projectPath:o,aclPermissionList:i,allDeviceIds:s,certIds:a,keyAlias:c,keyPwd:l}=e;if(s==null||s.length===0)throw new Error(E.DEVICE_LIST_EMPTY);let d=`${ee.BASE_URL}${ee.PROVISION_ADD_TEST_PATH}`,h=YN(t,r),w=await XN(n,d,a||[],r,s,h,i||[]);if(!w||!w.profileInfo||!w.profileInfo.provisionFileUrl)throw Kt("add provision failed, the provision file url is null"),new Error(E.ADD_PROFILE_FAIL);let S=w.profileInfo,se=(await tL(n,S.provisionFileUrl)).urlList,Ue=w.profileInfo.id;if(se&&se.length>0){let nt=await Dw(t,o),rt=nt.profilePath;if(!await nL(se,rt))throw await Yw(n,Ue),new Error(E.ERROR_WHILE_DOWNLOAD_PROFILE);if(await Yw(n,Ue),or.existsSync(nt.certPath)&&or.existsSync(rt)&&or.existsSync(nt.p12Path)){let fc=or.readFileSync(nt.certPath,"utf8"),mc=or.readFileSync(rt,"utf8");return rL(mc,fc,nt.p12Path,c,l)||eL(rt),rt}}throw new Error(E.ADD_PROFILE_FAIL)}function YN(n,e){let t=n?`${n}_`:"";return`${KN(`${t}${e}_${e}`)}`}function KN(n){return VN("sha256").update(n).digest("hex").substring(0,16)}async function XN(n,e,t,r,o,i,s){ZN(r);let a=gu(n),c={certList:t,packageName:r,deviceList:o,provisionName:i};s.length&&(c.aclPermissionList=s);let l=await x.postAllowFailure(e,{headers:a,params:c});if(!l)throw Kt("add provision failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(l.statusCode!==200)throw hu(l.statusCode,l.statusText,l.data);let d=JSON.parse(l.data);if(!d||!d.ret||d.ret.code!==0)throw Kt(`add provision fail: ${l.data}`),QN(l.data,i),new Error(d.ret?.msg||E.ADD_PROFILE_FAIL);let h=d.provisionFileUrl;return{profileInfo:{id:d.id,name:i,provisionFileUrl:h}}}function hu(n,e,t){return n===mt.FORBIDDEN?e===ye.OPENPROXY_BLOCKED_URL?new Error(E.ERR_CERT_NETWORK_ERROR):new Error(E.ERR_FORBIDDEN):n===mt.UNAUTHORIZED?new Error(E.ERR_UNAUTHORIZED):t.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE)?new Error(E.TEST_PROVISION_EXCEEDS_LIMIT):new Error(E.ADD_PROFILE_FAIL)}function ZN(n){if(!n||n.trim().length===0)throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE);if(!He.BUNDLE_NAME_REGEX.test(n))throw new Error(E.ERROR_SIGN_BUNDLE_NAME_VALIDATE)}function QN(n,e){if(n.includes(ye.PROVISION_EXCEEDS_LIMIT_CODE))throw new Error(E.TEST_PROVISION_EXCEEDS_LIMIT);if(n.includes(ye.PROVISION_NAME_REPEAT_CODE)&&e)throw new Error(E.PROFILE_NAME_REPEAT)}async function Yw(n,e){if(!e||e.trim().length===0)return;let t=`${ee.BASE_URL}${ee.PROVISION_DELETE_PATH}?id=${e}`,r=await x.deleteAllowFailure(t,{headers:gu(n)});if(r.statusCode!==200)throw hu(r.statusCode,r.statusText,r.data);let o=JSON.parse(r.data);(!o||!o.ret||o.ret.code!==0)&&Kt(`delete provision failed: ${r.data}`)}function eL(...n){for(let e of n)try{or.existsSync(e)&&or.unlinkSync(e)}catch(t){Kt(`delete local sign file error: ${t.message}`)}}async function tL(n,e){let t=`${ee.BASE_URL}${ee.CERT_DOWNLOAD_URL_PATH}`,r=gu(n),o={sourceUrls:e},i=await x.postAllowFailure(t,{headers:r,params:o});if(!i)throw Kt("get download list failed: response is null"),new Error(E.ADD_PROFILE_FAIL);if(i.statusCode!==200)throw hu(i.statusCode,i.statusText,i.data);let s=JSON.parse(i.data);if(!s||!s.urlsInfo||s.urlsInfo.length===0)throw Kt("download: The application does not exist"),new Error(s.ret?.msg||E.ADD_PROFILE_FAIL);return{urlList:s.urlsInfo,hasPermission:!0}}async function nL(n,e){if(!n||n.length===0)return!1;let t=n[0].newUrl;return await Ci(t,e),!0}function rL(n,e,t,r,o){return oL(n,e),r=r||He.TARGET_FRIENDLY_NAME,o=o||"",iL(e,t,r,o),!0}function oL(n,e){if(e.lastIndexOf(He.CERT_BEGIN_HEADER)<0)throw new Error(E.ERROR_WHILE_PARSE_PROFILE);let t=JSON.stringify(e.substring(e.lastIndexOf(He.CERT_BEGIN_HEADER))).replace(/\\r/g,"");if(!n.includes(t))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT);return!0}function iL(n,e,t,r){let o=n.matchAll(He.CERTIFICATE_PATTERN_GLOBAL),i=[],s=new Date;for(let c of o)try{let l=c[0],d=sL(l),h=new Date(d.validFrom),w=new Date(d.validTo);if(s<h||s>w){let S=`Certificate is not valid, Valid from ${h} to ${w}`;throw console.warn(`checkCertificateInValidityPeriod: ${S}`),new Error(E.CERTIFICATE_HAS_EXPIRED)}i.push(d)}catch(l){throw console.warn(`checkCertificateInValidityPeriod\uFF1A ${l.message}`),new Error(E.CERTIFICATE_HAS_EXPIRED,{cause:l})}if(!i||i.length===0)throw new Error(E.CERTIFICATE_HAS_EXPIRED);if(!cL(e,t,r,i))throw new Error(E.CERTIFICATION_AND_PROFILE_NOT_INCONSISTENT)}function sL(n){let e="-----BEGIN CERTIFICATE-----",t=n.trim();try{if(t.startsWith(e))return new mu(t);let r=Kw.from(t,"base64");return new mu(r)}catch(r){throw new Error("decodeBase64ToX509Certificate",{cause:r})}}function aL(n){if(n.cert){let e=ir.pki.publicKeyToPem(n.cert.publicKey);return zN(e).export({type:"spki",format:"der"})}if(n.asn1)try{let e=ir.asn1.toDer(n.asn1).getBytes(),t=Kw.from(e,"binary");return new mu(t).publicKey.export({type:"spki",format:"der"})}catch(e){return Kt(`Failed to parse cert from asn1: ${e}`),null}return null}function cL(n,e,t,r){try{let o=JN(n),i=ir.asn1.fromDer(ir.util.createBuffer(o)),c=ir.pkcs12.pkcs12FromAsn1(i,t).getBags({bagType:ir.pki.oids.certBag})[ir.pki.oids.certBag]||[];for(let l of c){let d=l.attributes?.friendlyName?.[0];if(!d||d.toLowerCase()!==e.toLowerCase())continue;let h=aL(l);if(!h)continue;if(r.some(S=>{let A=S.publicKey.export({type:"spki",format:"der"});return h.equals(A)}))return!0}return!1}catch(o){let i=o instanceof Error?o.message:String(o);return Kt(`Failed to process P12 file: ${n}, error: ${i}`),!1}}function gu(n){return{uid:n.uid,teamId:n.teamId,oauth2Token:n.accessToken}}var Qw="https://developer.huawei.com",lL={"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"},dL="/consumer/cn/doc/harmonyos-guides/restricted-permissions";function uL(n){let e=lL[n];return e?`${Qw}${e}`:void 0}function pL(){return`${Qw}${dL}`}var fL={"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 Zw(n,e){return(fL[n]??n).replace(/\{(\d+)\}/g,(r,o)=>String(e[Number(o)]??""))}function mL(n){return Array.from(n).join(", ")}function ev(n,e){if(n.size===0)return;let t=kn.getAclPermissionInfos(e),r=new Set;for(let h of t)n.has(h.permissionName)&&r.add(h);for(let h of r){let w=uL(h.permissionName);w!=null&&(h.permissionHelpUrlKey=w)}let o=new Set;for(let h of r)o.add(h.permissionDisplayName);let i=new Set;for(let h of r)if(h.permissionHelpUrlKey!=null){let w=h.permissionInsteadName??h.permissionDisplayName;i.add(`${w} (${h.permissionHelpUrlKey})`)}let s=pL(),a=Zw("acl.can.apply.text",[]),c=s?`${a} (${s})`:a,l=i.size>0?Array.from(i).join(", ")+".":"",d=Zw("acl.permissions.warn",[mL(o),l,c]);console.log(d)}var cc=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=G.discover(process.cwd()),{passed:!0,message:""}}catch(t){return m(`[EnvCheck] Project.discover() failed: ${t.message}`),e(X.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:X.ATOMIC_SERVICE_UNSUPPORTED}:{passed:!0,message:""}}};import hL from"fs";import tv from"path";var lc=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(X.JAVA_PLATFORM_UNSUPPORTED)}}checkHapSignTools(e){let t=this.toolProvider.sdkPath,r=b()?"hap-sign-tool":"hap-sign-tool.jar",o=tv.join(t,"default","openharmony","toolchains","lib",r);if(!hL.existsSync(o)){let i=tv.join("sdk","default","openharmony","toolchains","lib",r);return e(`${r} not found.Check whether ${i} exists.`)}return{passed:!0,message:""}}};var dc=class{_userInfo=null;async ensureUserInfo(){if(!this._userInfo)try{this._userInfo=await De.getUserInfo()}catch(e){return m(`[EnvCheck] Failed to load user info: ${e.message}`),null}return this._userInfo}async checkLogin(e){try{return await De.isLoggedIn()?(await this.ensureUserInfo(),{passed:!0,message:""}):e(X.LOGIN_REQUIRED)}catch(t){return m(`[EnvCheck] Login check failed: ${t.message}`),e(X.LOGIN_REQUIRED)}}async checkTeamInfo(e){if(!await this.ensureUserInfo())return e(X.TEAM_INFO_FAILED);try{if((await sn()).teamList.length>0)return{passed:!0,message:""}}catch(r){return m(`[EnvCheck] Team API error: ${r.message}`),e(X.TEAM_INFO_FAILED)}return m("[EnvCheck] No teams found for current user"),e(X.TEAM_INFO_FAILED)}async checkRealname(e){let t=await this.ensureUserInfo();return t?t.isRealName===!1?e(X.REALNAME_REQUIRED):t.isRealName!==!0?(m("[EnvCheck] Scenario 3 Real-name check: AGC API did not return realName field"),e(X.REALNAME_REQUIRED)):{passed:!0,message:""}:e(X.SESSION_EXPIRED)}async checkTeamId(e){let t=await this.ensureUserInfo();if(!t)return{passed:!0,message:""};let r=e??"";try{let o=await sn();if(r=e??(o.teamList.length>0?o.teamList[0].id:t.userId)??"",!o.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(o){return m(`[EnvCheck] Team ID check failed: ${o.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(X.REGION_CHINA_ONLY):{passed:!0,message:""}:(m("[EnvCheck] Scenario 12 Region check: AGC API did not return nationalCode field"),e(X.REGION_CHINA_ONLY)):e("User session expired or token invalid. Please login again.")}};async function gL(n){try{let{teamList:e}=await sn();if(e.length>0)return e[0].id}catch(e){m(`[EnvCheck] resolveDefaultTeamId failed: ${e.message}`)}return n??""}async function yL(n){let e=await De.getUserInfo(),t=await De.refreshToken();if(!e||!t?.accessToken)throw new Error("Not logged in");let r=n||await gL(e.userId);if(!r)throw new Error("No team found");let o={uid:e.userId??"",teamId:r,accessToken:t.accessToken};return(await ac(o)).map(s=>({deviceId:s.udid,deviceName:s.deviceName}))}var uc=class{constructor(e){this.toolProvider=e}toolProvider;async checkDevice(e,t){try{let r=await yL(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 i=await ne.from(this.toolProvider).listDevices();return i.length===0?(m("[EnvCheck] Scenario 4 Device check: no local devices found"),e(X.DEVICE_MISSING)):i.some(a=>jn(a.serial))?{passed:!0,message:""}:(m("[EnvCheck] Scenario 4 Device check: local device found but not an emulator"),e(X.DEVICE_MISSING))}catch(r){return m(`[EnvCheck] Scenario 4 Device check failed: ${r.message}`),e(X.DEVICE_DETECT_FAILED)}}};var pc=class{projectChecker=new cc;toolchainChecker=null;authChecker=new dc;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=i=>(i.passed||this.fail(i),!0),o=[()=>this.authChecker.checkLogin(t),()=>this.authChecker.checkTeamInfo(t),()=>this.authChecker.checkRealname(t)];for(let i of o)if(!r(await i()))return!1;return!(e.teamId&&!r(await this.authChecker.checkTeamId(e.teamId)))}async initToolchain(){try{let e=await I.new();return this.toolchainChecker=new lc(e),this.deviceChecker=new uc(e),!0}catch(e){throw m(`[EnvCheck] ToolProvider.new() failed: ${e.message}`),new Error(X.TOOLCHAIN_INIT_FAILED,{cause:e})}}async runDeviceCheck(e,t){return(o=>o.passed?!0:(this.fail(o),!1))(await this.deviceChecker.checkDevice(t,e.teamId))}async runProjectChecks(e,t){let r=i=>i.passed?!0:(this.fail(i),!1);if(!r(this.projectChecker.checkProjectDir(t))||!r(this.projectChecker.checkAtomicService()))return!1;let o=[()=>this.projectChecker.checkProduct(e.productName,t),()=>this.projectChecker.checkBundleName(e.productName,t),()=>this.toolchainChecker.checkJava(t),()=>this.toolchainChecker.checkHapSignTools(t)];for(let i of o)if(!r(i()))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 bL(n){if(wu.existsSync(n)){let e=wu.readFileSync(n,"utf-8");return SL.parse(e)}return{app:{signingConfigs:[],products:[]}}}function EL(n){n.app||(n.app={signingConfigs:[],products:[]}),n.app.signingConfigs||(n.app.signingConfigs=[]),n.app.products||(n.app.products=[])}async function PL(n){if(n.keyPwd===n.storePassword){let r=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath);return{keyPassword:r,storePassword:r}}let e=await Tn.encryptedPassword(n.keyPwd,n.p12FilePath),t=await Tn.encryptedPassword(n.storePassword,n.p12FilePath);return{keyPassword:e,storePassword:t}}async function CL(n,e,t){let r=nv.join(n,"build-profile.json5"),o=bL(r);EL(o);let i=t??"default",{keyPassword:s,storePassword:a}=await PL(e),c={name:i,type:"HarmonyOS",material:{certpath:e.cerFilePath,keyAlias:e.keyAlias,keyPassword:s,profile:e.profileFilePath,signAlg:ht.signAlg,storeFile:e.p12FilePath,storePassword:a}},l=o.app?.signingConfigs?.findIndex(h=>h.name===i);l!==void 0&&l>=0?o.app.signingConfigs[l]=c:o.app.signingConfigs.push(c);let d=o.app?.products?.findIndex(h=>h.name===i);d!==void 0&&d>=0?o.app.products[d].signingConfig=i:o.app.products.push({name:i,signingConfig:i}),wu.writeFileSync(r,JSON.stringify(o,null,2),"utf-8")}async function IL(n){let e=await De.getUserInfo(),t=await De.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 AL(n){let e=n.product||"default";await new pc().preflight({productName:e,teamId:n.teamId}),console.log("Executing signature generate command");let r=await IL(n),o=await I.new(),{shouldRegenerate:i}=await Di.shouldRegenerate({force:n.force??!1,teamId:r.teamId,productName:n.product},o);if(!i){console.log(yu("Signature generation completed successfully."));return}await DL(n,r,o),console.log(yu("Signature generation completed successfully."))}async function DL(n,e,t){let r=await ou(e,n.product),o=RL(n,e,r,t);o.allDeviceIds=await Gw(e,t.hdcPath),await Xw(e,o);let i=G.discover(process.cwd()).rootDir;await CL(i,r,n.product??"default"),console.log(yu(`Signing config written to ${nv.join(i,"build-profile.json5")}`))}function RL(n,e,t,r){let o=process.cwd(),i=G.discover(o),s=ic(i,r);return ev(s,i),{productName:n.product||"default",bundleName:i.getBundleName(),projectPath:i.rootDir,teamId:e.teamId,force:n.force||!1,aclPermissionList:[...s],certIds:[t.certId],keyAlias:t.keyAlias,keyPwd:t.keyPwd}}var rv=new wL("signature").description("Generate application signature.");rv.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 AL(n)}catch(e){console.error(vL(e.message)),process.exit(1)}});var ov=rv;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";TL();ie.name("devecocli").description("HarmonyOS application development command line tool").version("0.3.0");ie.addCommand(rp);ie.addCommand(Lp);ie.addCommand(Fp);ie.addCommand(Kp);ie.addCommand(Vf);ie.addCommand(ym);ie.addCommand(bm);ie.addCommand(xm);ie.addCommand(Hm);ie.addCommand(ih);ie.addCommand(gy);ie.addCommand(ov);ie.addCommand(vw);ie.addCommand(Uy);b()||ie.addCommand(Cf);var vu=process.argv.slice(2);vu.length>=2&&vu[vu.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var xL=new Set(["update","auth"]);ie.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==ie;)t=t.parent;xL.has(t.name())||await I.checkVersion()});ie.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(kL(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
|