@deveco-test/deveco-cli 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +19 -19
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -16,9 +16,9 @@ ${i.join(`
|
|
|
16
16
|
`+li("Build completed successfully!"))}catch(e){console.error(qn(e.message)),process.exit(1)}});ui.command("clean").description("Clean the HarmonyOS project build outputs").action(async()=>{try{let r=process.cwd(),e=Ae.discover(r);console.warn(di("Please ensure the project source is trustworthy before proceeding."));let t=await N.new(),n=new ke(t,e.rootDir);await dt(e.rootDir,async()=>{console.log(`
|
|
17
17
|
[1/2] Running hvigor clean...`);try{await n.clean()}catch(i){ut("hvigor clean",i)}console.log(`
|
|
18
18
|
[2/2] Running hvigor --stop-daemon...`);try{await n.stopDaemon()}catch(i){ut("hvigor --stop-daemon",i)}},()=>{console.log("Another build is already running for this project. Waiting for it to finish...")}),console.log(`
|
|
19
|
-
`+li("Clean completed successfully!"))}catch(r){console.error(qn(r.message)),process.exit(1)}});var pi=ui;import{Command as va}from"commander";import{green as wi,red as wa,yellow as ba}from"colorette";import{randomUUID as ga}from"crypto";import{execa as ya}from"execa";import{execa as
|
|
19
|
+
`+li("Clean completed successfully!"))}catch(r){console.error(qn(r.message)),process.exit(1)}});var pi=ui;import{Command as va}from"commander";import{green as wi,red as wa,yellow as ba}from"colorette";import{randomUUID as ga}from"crypto";import{execa as ya}from"execa";import{execa as fa}from"execa";import{execFile as ia,spawn as oa}from"child_process";import{promisify as sa}from"util";var aa=sa(ia);function hi(r,e,t){let i=r.replace(/\r\n/g,`
|
|
20
20
|
`).split(`
|
|
21
|
-
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function
|
|
21
|
+
`),o=i.pop()??"",s=i.map(a=>a.endsWith("\r")?a.slice(0,-1):a).filter(a=>a.length>0);return s.length>0&&t.onData(s,e),o}function mi(r,e,t){let n=r.endsWith("\r")?r.slice(0,-1):r;n.length>0&&t.onData([n],e)}function ca(r,e){return{stdout:r.stdoutChunks.join(""),stderr:r.stderrChunks.join(""),exitCode:e??0}}function la(){return{stdoutChunks:[],stderrChunks:[],stdoutLineBuffer:"",stderrLineBuffer:"",settled:!1}}function da(r,e,t,n,i){r.stdout?.on("data",o=>{let s=o.toString();e.stdoutChunks.push(s),e.stdoutLineBuffer=hi(e.stdoutLineBuffer+s,"stdout",t)}),r.stderr?.on("data",o=>{let s=o.toString();e.stderrChunks.push(s),e.stderrLineBuffer=hi(e.stderrLineBuffer+s,"stderr",t)}),r.on("error",o=>{e.settled||(e.settled=!0,t.onError(o),i(o))}),r.on("close",o=>{if(e.settled)return;e.settled=!0,mi(e.stdoutLineBuffer,"stdout",t),mi(e.stderrLineBuffer,"stderr",t),t.onClose(o);let s=ca(e,o);s.exitCode!==0&&t.onError(new Error(`Command process exited with code ${s.exitCode}`)),n(s)})}async function fi(r,e=[],t={}){try{let{stdout:n,stderr:i}=await aa(r,e,t);return{stdout:typeof n=="string"?n.trim():"",stderr:typeof i=="string"?i.trim():"",exitCode:0}}catch(n){let i=n;return{stdout:i.stdout?.trim()||"",stderr:i.stderr?.trim()||i.message,exitCode:typeof i.code=="number"?i.code:1}}}async function gi(r,e,t){return await new Promise((n,i)=>{let o=oa(r,e,{stdio:["inherit","pipe","pipe"]}),s=la();da(o,s,t,n,i)})}function yi(r){let e=r.trim(),t=e.indexOf("=");return t!==-1?e.slice(t+1).trim():e}var ua=[/communication channel is being established/i,/please wait for several seconds and try again/i,/device offline/i,/\[E0+04\]/i],pa=[/\[fail\]/i,/\bfail!/i,/not found/i];function _e(r){return r?ua.some(e=>e.test(r))?"transient":pa.some(e=>e.test(r))?"fatal":"ok":"ok"}var Jn=[800,1500,2500];function ha(r){return new Promise(e=>setTimeout(e,r))}async function ye(r,e){let t=1+Jn.length,n={stdout:"",stderr:"",exitCode:-1};for(let i=0;i<t;i++){n=await fi(r,e);let o=n.exitCode===0?n.stdout:n.stderr||n.stdout;if(_e(o)!=="transient"||i>=t-1)return n;w(`hdc transient failure on \`${e.join(" ")}\`: retrying in ${Jn[i]}ms`),await ha(Jn[i])}return n}async function Xn(r,e,t){let n=await ye(r,["-t",e,"shell","param","get",t]);if(n.exitCode!==0)return;let i=n.stdout.trim();if(!(!i||_e(i)!=="ok"))return yi(i)}var Kn="__DEVECO_PARAM_DELIM__";function ma(r,e){let t=new Map,n=r.split(Kn);for(let i=0;i<e.length;i++){let o=(n[i]??"").trim();if(!o||_e(o)!=="ok")continue;let s=yi(o);s&&t.set(e[i],s)}return t}async function We(r,e,t){if(t.length===0)return new Map;if(t.length===1){let o=new Map,s=await Xn(r,e,t[0]);return s&&o.set(t[0],s),o}let n=t.map(o=>`param get ${o}`).join(`; echo ${Kn}; `)+`; echo ${Kn}`,i=await ye(r,["-t",e,"shell",n]);return i.exitCode!==0?new Map:ma(i.stdout,t)}function pt(r){return r.startsWith("127.0.0.1:")}var vi=["ohos.qemu.hvd.name","const.product.name","const.product.model","const.product.brand","const.product.devicetype"],B=class r{hdcPath;constructor(e){this.hdcPath=e}static from(e){return new r(e.hdcPath)}static withHdcPath(e){return new r(e)}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}stripBrandPrefix(e,t){let n=e.trim(),i=t?.trim();if(!n||!i)return n;let o=new RegExp(`^${this.escapeRegExp(i)}(\\s+|[-_]+)?`,"i");return n.replace(o,"").trim()||n}async executeHdc(e){return fa(this.hdcPath,e,{stdio:["ignore","pipe","pipe"]})}async listDevices(){let{stdout:e}=await this.executeHdc(["list","targets"]),t=[];for(let n of e.split(`
|
|
22
22
|
`)){let i=n.trim();if(!i||i.startsWith("[Empty]"))continue;let o=i.split(/\s+/),s=o[0];!s||s.startsWith("[Empty]")||t.push({serial:s,status:o.length>=2?o[1]:"device"})}return t}extractDisplayName(e){let t=e.get("ohos.qemu.hvd.name");if(t)return t;let n=e.get("const.product.name");if(n&&n!=="emulator")return n;let i=e.get("const.product.model");if(i&&i!=="emulator"){let o=e.get("const.product.brand");return this.stripBrandPrefix(i,o)}}async getDeviceName(e){let t=await We(this.hdcPath,e,[...vi]);return this.extractDisplayName(t)??e}async getDeviceInfo(e,t){if(e.length===0)return null;if(t){let n=e.find(s=>s.serial===t);if(n)return n;let i=t.toLowerCase(),o=[];for(let s of e){let a=await this.getDeviceName(s.serial);a.toLowerCase().includes(i)&&o.push({device:s,name:a})}if(o.length===1)return o[0].device;throw o.length>1?new Error(`Multiple devices match "${t}". Please use a serial instead:
|
|
23
23
|
`+o.map(s=>` - ${s.name} (${s.device.serial})`).join(`
|
|
24
24
|
`)):new Error(`Device "${t}" not found. Use \`devecocli device list\` to see available targets.`)}return e[0]}async getDeviceDetail(e){let t={serial:e,status:"device"};try{let n=await We(this.hdcPath,e,["const.product.devicetype","const.ohos.apiversion","const.ohos.releasetype"]);t.deviceType=n.get("const.product.devicetype");let i=n.get("const.ohos.apiversion"),o=n.get("const.ohos.releasetype");i&&(t.osVersion=o?`API ${i} (${o})`:`API ${i}`)}catch{}return t}async listDevicesWithName(){let e=await this.listDevices();return Promise.all(e.map(async t=>({serial:t.serial,name:await this.getDeviceName(t.serial)})))}async getConnectedEntries(){let e=await this.listDevices();return Promise.all(e.map(t=>this.buildConnectedEntry(t.serial)))}async buildConnectedEntry(e){let t=pt(e),n,i;try{let o=await We(this.hdcPath,e,[...vi]);n=this.extractDisplayName(o),i=o.get("const.product.devicetype")}catch{}return{serial:e,name:n,isEmulator:t,deviceType:i}}};var Ht=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}async runHdc(e,t=!0){let n=this.toolProvider.hdcPath;w(`Executing: ${n} ${e.join(" ")}`);try{let{stdout:i}=await ya(n,e,{env:{...process.env}});return i}catch(i){if(t)throw i;return i.stdout||""}}async listTargets(){return(await this.deviceManager.listDevicesWithName()).map(t=>({name:t.name,id:t.serial}))}async uninstallApp(e,t){let n=await this.runHdc(["-t",e,"shell","bm","uninstall","-n",t],!1);if(n.includes("uninstall bundle successfully"))return!0;if(n.includes("uninstall missing installed bundle"))return!1;throw new Error(`Uninstall failed: ${n}`)}async installApp(e,t){if(t.length===0)return;let i=`/data/local/tmp/${ga()}`;try{await this.runHdc(["-t",e,"shell","mkdir",i]);for(let s of t){let a=await this.runHdc(["-t",e,"file","send",s,i+"/"]);if(!a.startsWith("FileTransfer finish"))throw new Error(a)}let o=await this.runHdc(["-t",e,"shell","bm","install","-p",i]);if(!o.includes("install bundle successfully."))throw new Error(o);console.log("App installed successfully")}finally{await this.runHdc(["-t",e,"shell","rm","-rf",i],!1)}}async launchApp(e,t,n){let i=["-t",e,"shell","aa","start","-a",n,"-b",t];return await this.runHdc(i)}};function Sa(r){let e=r.indexOf("@"),t=e!==-1?r.substring(0,e):r,n=e!==-1?r.substring(e+1):"default";return{moduleName:t,targetName:n}}async function Pa(r,e){let t=await r.listDevices();if(t.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");if(!e&&t.length>1){let i=await r.listDevicesWithName();throw new Error("Multiple devices found. Please specify a target device using `--device <Name>` or `--device <ID>`.\nAvailable devices:\n"+i.map(o=>` - ${o.name} (${o.serial})`).join(`
|
|
@@ -28,7 +28,7 @@ Available runnable modules:
|
|
|
28
28
|
`))}function Da(r,e,t,n,i){let o=[],s=r.collectNonHarDependentModuleList(e);for(let c of s){let d=r.findArtifactPath(c,t,n,i);o.push(d)}let a=r.findArtifactPath(e,t,n,i);return o.push(a),o}async function Ia(r,e,t,n,i,o){o&&(console.log(`Uninstalling ${t}...`),await r.uninstallApp(e,t)||console.log(`App ${t} is not installed, skipping uninstall.`)),console.log(`
|
|
29
29
|
Installing artifacts to device ${e}...`),await r.installApp(e,n),console.log(`Launching ${t}/${i}...`);let s=await r.launchApp(e,t,i);console.log(wi(`
|
|
30
30
|
Application '${t}': ${s}`))}var Ca=new va("run").description("Build and run the project on a connected device").option("--module <module>","Module 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 (e.g. debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip the build step and deploy the existing artifacts").action(async r=>{try{await ka(r)}catch(e){console.error(wa(e.message)),process.exit(1)}});async function Aa(r,e,t,n,i,o){let s=new $e(e,r.rootDir),a=new ke(e,r.rootDir),d=r.collectNonHarDependentModuleList(t).map(k=>`${k}@${n}`),u=Yn(r,d),b={type:"modules",modulesToBuild:d,moduleTasks:u};await dt(r.rootDir,()=>Gn(s,a,i,o,b),()=>console.log("Another build is already running for this project. Waiting for it to finish...")),console.log(`
|
|
31
|
-
`+wi("Build completed successfully!"))}async function ka(r){let e=Ae.discover(process.cwd());console.warn(ba("Please ensure the project source is trustworthy before proceeding."));let t=await N.new(),n=Ea(e,r.module),{moduleName:i,targetName:o}=Sa(n),s=e.getModuleType(i);if(s!=="entry"&&s!=="feature"&&s!=="shared")throw new Error(`Module '${i}' is of type '${s}', which is not runnable. Please specify an entry or feature module.`);let a=new Ht(t),c=B.from(t),d=await Pa(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),b=r.product||"default",k=r.buildMode||"debug";r.skipBuild||await Aa(e,t,i,o,b,k);let ce=Da(e,i,o,u,b),je=e.getBundleName(),Fe=e.getMainAbility(i,r.ability);await Ia(a,d,je,ce,Fe,!!r.uninstall)}var bi=Ca;import{Command as Ta}from"commander";import{green as Si,red as Pi,cyan as Zn}from"colorette";import{execa as Ei}from"execa";function Ma(){return"@deveco-test/deveco-cli"}function xa(){return"0.6.
|
|
31
|
+
`+wi("Build completed successfully!"))}async function ka(r){let e=Ae.discover(process.cwd());console.warn(ba("Please ensure the project source is trustworthy before proceeding."));let t=await N.new(),n=Ea(e,r.module),{moduleName:i,targetName:o}=Sa(n),s=e.getModuleType(i);if(s!=="entry"&&s!=="feature"&&s!=="shared")throw new Error(`Module '${i}' is of type '${s}', which is not runnable. Please specify an entry or feature module.`);let a=new Ht(t),c=B.from(t),d=await Pa(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),b=r.product||"default",k=r.buildMode||"debug";r.skipBuild||await Aa(e,t,i,o,b,k);let ce=Da(e,i,o,u,b),je=e.getBundleName(),Fe=e.getMainAbility(i,r.ability);await Ia(a,d,je,ce,Fe,!!r.uninstall)}var bi=Ca;import{Command as Ta}from"commander";import{green as Si,red as Pi,cyan as Zn}from"colorette";import{execa as Ei}from"execa";function Ma(){return"@deveco-test/deveco-cli"}function xa(){return"0.6.1"}var Ra=new Ta("update").description("Update deveco-cli to the latest version").action(async()=>{let r=Ma(),e=xa();console.log(Zn("Checking for updates..."));try{let{stdout:t}=await Ei("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(Si(`
|
|
32
32
|
${r} is already up to date (version ${e})`));return}console.log(Zn(`
|
|
33
33
|
New version found: ${n} (current: ${e})`)),console.log(Zn(`Updating ${r}...`)),await Ei("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
|
|
34
34
|
`+Si(`${r} updated successfully to version ${n}!`))}catch(t){let n=t;console.error(Pi(`Failed to update ${r}`)),n.message&&console.error(Pi(n.message)),process.exit(1)}}),Di=Ra;import{Command as ec}from"commander";import{execa as nr}from"execa";function H(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Oa}from"child_process";var Na=2500;function La(r,e,t,n,i,o){r.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?n():i(a||`Emulator process exited with code ${s}`)})}function Ha(r,e,t,n){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners(),r.stderr?.destroy(),r.unref(),t())},c=u=>{if(!i){i=!0,clearTimeout(d),r.removeAllListeners(),r.stderr?.removeAllListeners();try{r.kill()}catch{}n(new Error(u))}},d=setTimeout(a,Na);r.once("error",u=>c(u.message)),La(r,d,s,a,c,o)}function Ii(r,e,t){return w(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=Oa(r,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),Ha(s,o,n,i)})}import*as Ue from"path";function ja(r){let e=new Set,t=[];for(let n of r){let i=JSON.stringify(n);e.has(i)||(e.add(i),t.push(n))}return t}function Fa(r){let e=r.instancePath?.trim();if(e)return Ue.dirname(Ue.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?Ue.dirname(Ue.normalize(t)).replace(/\\/g,"/"):""}function $a(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Ci(r,e){return e?[...r,"-bootmode",e]:r}function _a(r,e,t){let n=[Ci(["-start",r],t)],i=Fa(e);if(i)for(let o of $a(e.imageRoot))n.push(Ci(["-hvd",r,"-path",i,...o],t));return ja(n)}async function Ai(r,e,t,n){let i=new Error("No start strategy ran"),o=_a(r,e,n);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function Qn(r){return(await B.withHdcPath(r).listDevices()).map(t=>t.serial).filter(pt)}async function er(r){let e=await Qn(r);return e.length===0?[]:(await Promise.all(e.map(n=>Xn(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function ki(r,e){return(await er(r)).includes(e)}import*as ze from"path";import{existsSync as Wa,statSync as Ua}from"fs";function Be(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function Ba(r){let e=Be(r,["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,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return n.trim()}return""}function za(r){return Be(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Va(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=ze.dirname(ze.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=ze.join(t,n.name);Wa(i)&&Ua(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function qa(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=za(t),i=Be(t,["deviceType","DeviceType","devicetype"]),o=Be(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Ba(t),path:Be(t,["path","Path","hvdPath","hvd_path"]),imageRoot:Be(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function Ya(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,n=null,i;for(;(i=t.exec(r))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")n&&e.push(n),n={name:s.trim()};else if(n){let a=o.toLowerCase();a==="isrunning"?n.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?n.instancePath=s.trim():a==="path"?n.path=s.trim():a==="imageroot"?n.imageRoot=s.trim():a==="devicetype"?n.deviceType=s.trim():a==="os.osversion"&&(n.osVersion=s.trim())}}return n&&e.push(n),e}function Ti(r){let t=qa(r)??Ya(r);return Va(t),t}function tr(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function Ga(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Ja(r){if(!Ga(r))return null;let e=tr(r,["osVersion","OsVersion","OSVersion"]),t=tr(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=tr(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function jt(r){let e=r.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=[];for(let i of t){if(!i||typeof i!="object")continue;let o=Ja(i);o&&n.push(o)}return n}catch{return[]}}function Mi(r){let t=jt(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var xi=/no images are available/i;function ne(r){return r.normalize("NFKC").trim().toLowerCase()}function Ka(r){let e=r.message||"";return xi.test(e)}var Ve=class r{emulatorPath;sdkPath;hdcPath;constructor(e,t,n){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=n}static from(e){return new r(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return nr(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return Ii(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Ti(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let n of t)n.name&&n.deviceType&&e.set(H(n.name),n.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),n=H(e),i=t.find(a=>H(a.name)===n);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await Ai(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
|
|
@@ -1208,31 +1208,31 @@ Part II: Aland Islands, Albania, Andorra, Australia, Austria, Belgium, Bonaire,
|
|
|
1208
1208
|
\r
|
|
1209
1209
|
Part III: Other countries and regions.\r
|
|
1210
1210
|
---------------------------------------\r`;var hc=new Set,$t=new Map,ar="HarmonyOS_Software_Service_Agreement",$i=["Emulator license agreements are not accepted yet.","","Accept the agreements in an interactive terminal:"," devecocli emulator license accept","","To review the agreement text (read-only):"," devecocli emulator license view"].join(`
|
|
1211
|
-
`),_i=$i,cr="HarmonyOS_SDK_Agreement";function Wi(r,e){return`${r}\0${e}`}function
|
|
1211
|
+
`),_i=$i,cr="HarmonyOS_SDK_Agreement";function Wi(r,e){return`${r}\0${e}`}function mc(){hc.clear(),$t.clear()}var fc=$i,X=class extends Error{constructor(e=fc){super(e),this.name="EmulatorLicenseBlockedError"}};function Ui(r,e){return[r??"",e??""].join(`
|
|
1212
1212
|
`)}function Bi(r){let e=r.normalize("NFKC"),t=e.match(/(\d+)\.(\d+)\.\d+/);if(t)return`${t[1]}.${t[2]}`;let n=e.match(/(\d+)\.(\d+)\b/);return n?`${n[1]}.${n[2]}`:null}function gc(r){return`Emulator${r.trim()}`}function zi(r){let e=gc(r);if(process.platform==="win32"){let n=process.env.LOCALAPPDATA;if(!n)throw new Error("LOCALAPPDATA is not set; cannot resolve .emu_config path.");return Te.join(n,"Huawei",e,".emu_config")}if(process.platform==="darwin")return Te.join(sr.homedir(),"Library","Caches","Huawei",e,".emu_config");let t=process.env.XDG_CACHE_HOME?.trim()||Te.join(sr.homedir(),".cache");return Te.join(t,"Huawei",e,".emu_config")}async function yc(r,e,t){let n=Wi(r,e),i=$t.get(n);if(i!==void 0)return i;let o=await Fi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1024*1024}),s=Ui(o.stdout,o.stderr).trim();if(o.exitCode!==0||!s)throw new X(t);return $t.set(n,s),s}function vc(r){let e=r[0],t=r[r.length-1];return(e==='"'||e==="'")&&e===t?r.slice(1,-1):r}function wc(r){try{let e=JSON.parse(r);if(e&&typeof e=="object"&&!Array.isArray(e)){let t={};for(let[n,i]of Object.entries(e))t[n]={value:typeof i=="string"?i:String(i),delimiter:"json"};return t}}catch{return}}function bc(r){let e=r.trim();if(!(!e||e.startsWith("#")))for(let t of["=",":"]){let n=e.indexOf(t);if(n<=0)continue;let i=e.slice(0,n).trim();if(!i||t===":"&&i.includes("//"))continue;let o=vc(e.slice(n+1).trim());return{key:i,entry:{value:o,delimiter:t}}}}function Sc(r){let e={};for(let t of r.split(/\r?\n/)){let n=bc(t);n&&(e[n.key]=n.entry)}return e}function Pc(r){let e=r.trim();if(!e)return{};let t=wc(e);return t||Sc(r)}function Ec(r){return typeof r!="string"?!1:r.normalize("NFKC").trim().toLowerCase()==="agree"}async function Vi(r,e,t,n){let i=await yc(r,e,n),o=Bi(i);if(!o)throw new X(n);let s=zi(o),a;try{a=await ve.readFile(s,"utf8")}catch(u){throw u.code==="ENOENT"?new X(n):u}let d=Pc(a)[t];if(!d)throw new X(n);if(d.delimiter==="=")throw new X(n);if(!Ec(d.value))throw new X(n)}async function qi(r,e){await Vi(r,e,ar,_i)}async function Yi(r,e){await Vi(r,e,cr,_i)}async function Dc(r,e){let t=await Fi(r,["-version"],{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},reject:!1,maxBuffer:1048576}),n=Ui(t.stdout,t.stderr).trim();if(t.exitCode!==0||!n)throw new Error(`Emulator -version failed (exit ${String(t.exitCode)}); cannot resolve .emu_config path.`);let i=Wi(r,e);return $t.set(i,n),n}async function Ic(r,e){let t=await Dc(r,e),n=Bi(t);if(!n)throw new Error(`Cannot parse Emulator major.minor from:
|
|
1213
1213
|
${t}`);return zi(n)}function ji(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Cc(r,e,t){if(!t.startsWith("{"))return!1;try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n))return n[ar]="agree",n[cr]="agree",await ve.writeFile(r,`${JSON.stringify(n,null,2)}
|
|
1214
1214
|
`,"utf8"),!0}catch{}return!1}async function Ac(r,e){let t=ar,n=cr,i=[{k:t,re:new RegExp(`^\\s*${ji(t)}\\s*[:=]`)},{k:n,re:new RegExp(`^\\s*${ji(n)}\\s*[:=]`)}],o=e.length===0?[]:e.split(/\r?\n/),s=[],a=new Set;for(let c of o){let d=!1;for(let{k:u,re:b}of i)if(b.test(c)){s.push(`${u}:agree`),a.add(u),d=!0;break}d||s.push(c)}a.has(t)||s.push(`${t}:agree`),a.has(n)||s.push(`${n}:agree`),await ve.writeFile(r,s.join(`
|
|
1215
1215
|
`)+(s.length>0?`
|
|
1216
|
-
`:""),"utf8")}async function kc(r){await ve.mkdir(Te.dirname(r),{recursive:!0});let e="";try{e=await ve.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Cc(r,e,t)||await Ac(r,e)}async function Gi(r,e){return console.log(or),0}var Tc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Ji(r,e){if(console.log(or),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("devecocli emulator license accept requires an interactive terminal."),1;let n=pc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Tc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Ic(r,e);await kc(s),fc()}catch(s){return console.error(s.message),1}return 0}var xc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Rc(r){let e=r.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Oc(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid: use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)"'):new Error(`--os-version must start with "HarmonyOS " (e.g. HarmonyOS 5.1.1(19)). Got: "${r}"`)}function Nc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(re("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(re("Run `devecocli emulator image download ...` then `devecocli emulator image list` and copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===n)){console.error(z("--os-version does not match any downloaded image (exact string required).")),console.log(re("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${r}".`)}}var Lc=["Name","Status","Serial","Device Type","OS Version"];function Hc(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function jc(r,e){let t=await Promise.all(e.map(async n=>{let i=await We(r,n,xc);return[n,i]}));return new Map(t)}async function Fc(r){let e=await Qn(r),t=await jc(r,e);return{serials:e,params:t}}function $c(r,e,t,n,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function _c(r,e,t){let n=new Map,i=new Map,o=[...r],s=[...t];for(let a of r){let c=e.get(a),d=c?.get("ohos.qemu.hvd.name");d&&i.set(d,a),t.length>0&&$c(a,c,s,o,n)}for(let a=0;a<s.length&&a<o.length;a++)n.set(s[a],o[a]);return{productSerialMap:n,hvdSerialMap:i}}function Wc(r,e,t){let n=r.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return n.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),n.map(i=>Hc(i.emu,i.serial,i.effectiveRunning))}async function Uc(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),Fc(e)]);if(n.length===0){t?.stop(),console.log(re(" No emulator instances found.")),console.log(Ge(" You can create an emulator in DevEco Studio."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=_c(i.serials,i.params,o);t?.stop();let c=Wc(n,s,a);console.log(ht(Lc,c)),console.log("")}catch(n){Ft(t,`Failed to list emulators: ${n.message}`)}}function Zi(r,e,t){let n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(o.status!=="rejected")continue;n=!0;let s=o.reason;console.error(z(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Ge(s.stdout)),s.stderr&&console.error(Ge(s.stderr))}return n}var Bc=2e3,zc=6e4;async function Vc(r,e){let t=H(e);return(await er(r)).some(i=>H(i)===t)}async function Qi(r,e,t,n=zc,i=Bc){let o=Date.now()+n;for(;Date.now()<o;){if(await Vc(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function qc(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(re(`Emulator "${t}" is already running.`));return}console.log(Ye(`Starting emulator "${t}"...`));let i=await Qi(e,t,!0);console.log(i?_t(`Emulator "${t}" started successfully.`):re(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Yc(r,e,t){let n=await Promise.allSettled(t.map(o=>qc(r,e,o)));Zi(n,t,"start")&&process.exit(1)}async function Gc(r,e){let t=e.trim();if(!pt(t))return t;let n=await B.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function Jc(r,e,t){let n=await Gc(e,t);if(console.log(Ye(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(re(`Emulator "${n}" is already stopped.`));return}let o=await Qi(e,n,!1);console.log(o?_t(`Emulator "${n}" stopped successfully!`):re(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the timeout.`))}async function Kc(r,e,t){let n=await Promise.allSettled(t.map(o=>Jc(r,e,o))),i=Zi(n,t,"stop");console.log(""),i&&process.exit(1)}async function ie(){try{let r=await N.new();return{manager:Ve.from(r),toolProvider:r}}catch(r){console.error(z(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var we=new lr("emulator").description("Manage emulator instances"),Xc=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Wt(r){let e=new Xi("--device-type <type>","Emulator device type").choices([...Xc]);return r?e.makeOptionMandatory():e}function qe(r,e){for(let t of e)if(t in r)return r[t]}function ft(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function Ki(r){let e=ft(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Zc=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Qc="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function eo(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function to(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=ft(qe(i,["osVersion","OsVersion","OSVersion","os_version"])),s=ft(qe(i,["deviceType","DeviceType","device_type"])),a=Ki(qe(i,["downloaded","Downloaded","isDownloaded"])),c=ft(qe(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=ft(qe(i,["releaseType","ReleaseType","release_type"])),u=Ki(qe(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function el(r){let e=r.trim();if(!e)return!0;let t=eo(e);return t===null?!1:t.length===0?!0:to(t,!0).length===0}function tl(r,e){let t=r.trim();if(!t)return"";let n=eo(t);if(!n)return r.trimEnd();let i=to(n,e);return ht(Zc,i)}var Ut=new lr("image").description("HarmonyOS emulator system images (download, list, remove)");Ut.command("download").description("Download a system image").addOption(Wt(!1)).option("--os-version <version>","e.g. HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let{manager:e,toolProvider:t}=await ie();try{await Yi(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof X&&(console.error(z(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(z("error: required option '--device-type <type>' not specified")),process.exit(1)),r.osVersion?.trim()||(console.error(z("error: required option '--os-version <version>' not specified")),process.exit(1));try{await e.installEmulatorImage({deviceType:r.deviceType.trim(),osVersion:r.osVersion.trim(),force:r.force===!0})}catch(n){console.error(z(`Failed to download system image: ${n.message}`)),process.exit(1)}});Ut.command("remove").description("Remove a downloaded system image").addOption(Wt(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await ie();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(z(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Ut.command("list").description("List system images").addOption(Wt(!1)).option("--all","List all images (downloaded and not downloaded)").addOption(new Xi("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await ie();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(el(n)){console.log(re(Qc));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=tl(n,r.all===!0);console.log(i)}catch(t){console.error(z(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});we.addCommand(Ut);var dr=new lr("license").description("HarmonyOS local emulator license");dr.command("view").description("review the agreement text (read-only)").action(async()=>{let{toolProvider:r}=await ie(),e=await Gi(r.emulatorPath,r.sdkPath);process.exit(e)});dr.command("accept").description("review and accept the agreements").action(async()=>{let{toolProvider:r}=await ie(),e=await Ji(r.emulatorPath,r.sdkPath);process.exit(e)});we.addCommand(dr);we.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await ie(),t=Mc({text:"Listing emulators\u2026",color:"cyan"}).start();await Uc(r,e.hdcPath,t)});we.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await ie();try{await qi(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof X&&(console.error(z(n.message)),process.exit(1)),n}r?.length||(console.error(z("error: missing required argument 'names'")),process.exit(1)),await Yc(e,t.hdcPath,r)});we.command("stop <names...>").description("Stop one or more emulator instances (by name or 127.0.0.1:<port> serial)").action(async r=>{let{manager:e,toolProvider:t}=await ie();r?.length||(console.error(z("error: missing required argument 'names'")),process.exit(1)),await Kc(e,t.hdcPath,r)});var no=we.command("create <name>").description("Create a local emulator. Runs emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(Wt(!0)).requiredOption("--os-version <version>",'Exact downloaded image label. Quote in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or use --os-version="\u2026"; see `devecocli emulator image list`').option("--force","Overwrite if the tool supports it");no.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1216
|
+
`:""),"utf8")}async function kc(r){await ve.mkdir(Te.dirname(r),{recursive:!0});let e="";try{e=await ve.readFile(r,"utf8")}catch(n){if(n.code!=="ENOENT")throw n}let t=e.trim();await Cc(r,e,t)||await Ac(r,e)}async function Gi(r,e){return console.log(or),0}var Tc="Please read carefully and confirm whether agree to the above agreement? (y/N): ";async function Ji(r,e){if(console.log(or),!process.stdin.isTTY||!process.stdout.isTTY)return console.error("devecocli emulator license accept requires an interactive terminal."),1;let n=pc.createInterface({input:process.stdin,output:process.stdout}),i;try{i=await n.question(Tc)}finally{n.close()}let o=i.trim().toLowerCase();if(o!=="y"&&o!=="yes")return 1;try{let s=await Ic(r,e);await kc(s),mc()}catch(s){return console.error(s.message),1}return 0}var xc=["ohos.qemu.hvd.name","const.product.name","const.product.model"];function Rc(r){let e=r.trim();if(!e||!/^[A-Za-z0-9_ ]+$/.test(e))throw new Error("The virtual device name can only contain letters, spaces, numbers, and underscores (_).")}function Oc(r){let e=r.trim();if(!e)throw new Error("--os-version must not be empty.");if(/^\d+$/.test(e))throw new Error(`--os-version "${r}" is invalid: use the full image label, e.g. HarmonyOS 5.1.1(19).`);if(!/^HarmonyOS\s+/i.test(e))throw/^HarmonyOS$/i.test(e)?new Error('--os-version is incomplete (only "HarmonyOS"). On PowerShell/cmd, quote the full label, e.g. --os-version "HarmonyOS 6.0.1(21)"'):new Error(`--os-version must start with "HarmonyOS " (e.g. HarmonyOS 5.1.1(19)). Got: "${r}"`)}function Nc(r,e){let t=i=>i.normalize("NFKC").trim(),n=t(r);if(e.length===0)throw console.error(re("Could not parse any downloaded images from `emulator -imageList -downloaded true` (JSON array expected).")),console.error(re("Run `devecocli emulator image download ...` then `devecocli emulator image list` and copy an `osVersion` string exactly.")),new Error("No downloaded osVersion values parsed; cannot validate --os-version.");if(!e.some(i=>t(i)===n)){console.error(z("--os-version does not match any downloaded image (exact string required).")),console.log(re("Use one of these --os-version values:"));for(let i of e)console.log(` ${i}`);throw new Error(`No downloaded image matches --os-version "${r}".`)}}var Lc=["Name","Status","Serial","Device Type","OS Version"];function Hc(r,e,t){return{cells:[r.name,t?"running":"stopped",e??"-",r.deviceType??"-",r.osVersion??"-"],highlight:t}}async function jc(r,e){let t=await Promise.all(e.map(async n=>{let i=await We(r,n,xc);return[n,i]}));return new Map(t)}async function Fc(r){let e=await Qn(r),t=await jc(r,e);return{serials:e,params:t}}function $c(r,e,t,n,i){if(e)for(let o of["const.product.name","const.product.model"]){let s=e.get(o);if(!s)continue;let a=t.indexOf(s);if(a===-1)continue;t.splice(a,1),i.set(s,r);let c=n.indexOf(r);c!==-1&&n.splice(c,1);return}}function _c(r,e,t){let n=new Map,i=new Map,o=[...r],s=[...t];for(let a of r){let c=e.get(a),d=c?.get("ohos.qemu.hvd.name");d&&i.set(d,a),t.length>0&&$c(a,c,s,o,n)}for(let a=0;a<s.length&&a<o.length;a++)n.set(s[a],o[a]);return{productSerialMap:n,hvdSerialMap:i}}function Wc(r,e,t){let n=r.map(i=>({emu:i,serial:e.get(i.name)??t.get(i.name),effectiveRunning:i.isRunning===!0||t.has(i.name)}));return n.sort((i,o)=>i.effectiveRunning!==o.effectiveRunning?i.effectiveRunning?-1:1:i.emu.name.localeCompare(o.emu.name)),n.map(i=>Hc(i.emu,i.serial,i.effectiveRunning))}async function Uc(r,e,t){try{let[n,i]=await Promise.all([r.listEmulators(),Fc(e)]);if(n.length===0){t?.stop(),console.log(re(" No emulator instances found.")),console.log(Ge(" You can create an emulator in DevEco Studio."));return}let o=n.filter(d=>d.isRunning).map(d=>d.name),{productSerialMap:s,hvdSerialMap:a}=_c(i.serials,i.params,o);t?.stop();let c=Wc(n,s,a);console.log(ht(Lc,c)),console.log("")}catch(n){Ft(t,`Failed to list emulators: ${n.message}`)}}function Zi(r,e,t){let n=!1;for(let i=0;i<r.length;i++){let o=r[i];if(o.status!=="rejected")continue;n=!0;let s=o.reason;console.error(z(`Failed to ${t} emulator "${e[i]}": ${s.message}`)),s.stdout&&console.error(Ge(s.stdout)),s.stderr&&console.error(Ge(s.stderr))}return n}var Bc=2e3,zc=6e4;async function Vc(r,e){let t=H(e);return(await er(r)).some(i=>H(i)===t)}async function Qi(r,e,t,n=zc,i=Bc){let o=Date.now()+n;for(;Date.now()<o;){if(await Vc(r,e)===t)return!0;await new Promise(a=>setTimeout(a,i))}return!1}async function qc(r,e,t){if(await r.startEmulator(t)==="already-running"){console.log(re(`Emulator "${t}" is already running.`));return}console.log(Ye(`Starting emulator "${t}"...`));let i=await Qi(e,t,!0);console.log(i?_t(`Emulator "${t}" started successfully.`):re(`Emulator "${t}" was launched but did not appear in hdc list targets within the timeout.`))}async function Yc(r,e,t){let n=await Promise.allSettled(t.map(o=>qc(r,e,o)));Zi(n,t,"start")&&process.exit(1)}async function Gc(r,e){let t=e.trim();if(!pt(t))return t;let n=await B.withHdcPath(r).getDeviceName(t);if(n===t)throw new Error(`Cannot resolve a running emulator with serial "${t}". Use \`devecocli emulator list\` or pass the emulator name instead.`);return n}async function Jc(r,e,t){let n=await Gc(e,t);if(console.log(Ye(`Stopping emulator "${n}"...`)),await r.stopEmulator(n)==="already-stopped"){console.log(re(`Emulator "${n}" is already stopped.`));return}let o=await Qi(e,n,!1);console.log(o?_t(`Emulator "${n}" stopped successfully!`):re(`Emulator "${n}" stop signal was sent but the instance is still visible in hdc list targets within the timeout.`))}async function Kc(r,e,t){let n=await Promise.allSettled(t.map(o=>Jc(r,e,o))),i=Zi(n,t,"stop");console.log(""),i&&process.exit(1)}async function ie(){try{let r=await N.new();return{manager:Ve.from(r),toolProvider:r}}catch(r){console.error(z(`Failed to initialize emulator: ${r.message}`)),process.exit(1);return}}var we=new lr("emulator").description("Manage emulator instances"),Xc=["phone","foldable","widefold","triplefold","tablet","2in1","2in1 foldable","wearable","tv"];function Wt(r){let e=new Xi("--device-type <type>","Emulator device type").choices([...Xc]);return r?e.makeOptionMandatory():e}function qe(r,e){for(let t of e)if(t in r)return r[t]}function mt(r){return r==null?"":typeof r=="string"?r.trim():String(r).trim()}function Ki(r){let e=mt(r).toLowerCase();return e==="true"?"true":e==="false"?"false":e}var Zc=["OS Version","Device Type","Software Version","Release Type","Upgradable","Downloaded"],Qc="No matching system images found. Try `devecocli emulator image list --all`, then download an image via `devecocli emulator image download ...`.";function eo(r){try{let e=JSON.parse(r);return Array.isArray(e)?e:null}catch{return null}}function to(r,e){let t=[];for(let n of r){if(!n||typeof n!="object")continue;let i=n,o=mt(qe(i,["osVersion","OsVersion","OSVersion","os_version"])),s=mt(qe(i,["deviceType","DeviceType","device_type"])),a=Ki(qe(i,["downloaded","Downloaded","isDownloaded"])),c=mt(qe(i,["SoftWareVersion","SoftwareVersion","softwareVersion","software_version","version"])),d=mt(qe(i,["releaseType","ReleaseType","release_type"])),u=Ki(qe(i,["upgradable","Upgradable","isUpgradable"]));t.push({cells:[o,s,c,d,u,a],highlight:e&&a==="true"})}return t}function el(r){let e=r.trim();if(!e)return!0;let t=eo(e);return t===null?!1:t.length===0?!0:to(t,!0).length===0}function tl(r,e){let t=r.trim();if(!t)return"";let n=eo(t);if(!n)return r.trimEnd();let i=to(n,e);return ht(Zc,i)}var Ut=new lr("image").description("HarmonyOS emulator system images (download, list, remove)");Ut.command("download").description("Download a system image").addOption(Wt(!1)).option("--os-version <version>","e.g. HarmonyOS 5.1.1(19) or HarmonyOS 6.0.1(21) (required)").option("--force","Overwrite an existing image").action(async r=>{let{manager:e,toolProvider:t}=await ie();try{await Yi(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof X&&(console.error(z(n.message)),process.exit(1)),n}r.deviceType?.trim()||(console.error(z("error: required option '--device-type <type>' not specified")),process.exit(1)),r.osVersion?.trim()||(console.error(z("error: required option '--os-version <version>' not specified")),process.exit(1));try{await e.installEmulatorImage({deviceType:r.deviceType.trim(),osVersion:r.osVersion.trim(),force:r.force===!0})}catch(n){console.error(z(`Failed to download system image: ${n.message}`)),process.exit(1)}});Ut.command("remove").description("Remove a downloaded system image").addOption(Wt(!0)).requiredOption("--os-version <version>","Supports both image label (HarmonyOS x.y.z(n)) and softwareVersion").action(async r=>{let{manager:e}=await ie();try{await e.uninstallEmulatorImage({deviceType:r.deviceType,osVersion:r.osVersion})}catch(t){console.error(z(`Failed to remove system image: ${t.message}`)),process.exit(1)}});Ut.command("list").description("List system images").addOption(Wt(!1)).option("--all","List all images (downloaded and not downloaded)").addOption(new Xi("--format <format>","Output format").choices(["table","json"]).default("table")).action(async r=>{let{manager:e}=await ie();try{let t;r.all?t=void 0:t=!0;let n=await e.listEmulatorImages({deviceType:r.deviceType,downloaded:t});if(el(n)){console.log(re(Qc));return}if(r.format==="json"){console.log(n.trimEnd());return}let i=tl(n,r.all===!0);console.log(i)}catch(t){console.error(z(`Failed to list emulator images: ${t.message}`)),process.exit(1)}});we.addCommand(Ut);var dr=new lr("license").description("HarmonyOS local emulator license");dr.command("view").description("review the agreement text (read-only)").action(async()=>{let{toolProvider:r}=await ie(),e=await Gi(r.emulatorPath,r.sdkPath);process.exit(e)});dr.command("accept").description("review and accept the agreements").action(async()=>{let{toolProvider:r}=await ie(),e=await Ji(r.emulatorPath,r.sdkPath);process.exit(e)});we.addCommand(dr);we.command("list").description("List all emulator instances").action(async()=>{let{manager:r,toolProvider:e}=await ie(),t=Mc({text:"Listing emulators\u2026",color:"cyan"}).start();await Uc(r,e.hdcPath,t)});we.command("start [names...]").description("Start one or more emulator instances").action(async r=>{let{manager:e,toolProvider:t}=await ie();try{await qi(t.emulatorPath,t.sdkPath)}catch(n){throw n instanceof X&&(console.error(z(n.message)),process.exit(1)),n}r?.length||(console.error(z("error: missing required argument 'names'")),process.exit(1)),await Yc(e,t.hdcPath,r)});we.command("stop <names...>").description("Stop one or more emulator instances (by name or 127.0.0.1:<port> serial)").action(async r=>{let{manager:e,toolProvider:t}=await ie();r?.length||(console.error(z("error: missing required argument 'names'")),process.exit(1)),await Kc(e,t.hdcPath,r)});var no=we.command("create <name>").description("Create a local emulator. Runs emulator -create <name> \u2026; --os-version must match a downloaded image from `emulator image list`.").addOption(Wt(!0)).requiredOption("--os-version <version>",'Exact downloaded image label. Quote in PowerShell (e.g. "HarmonyOS 6.0.1(21)") or use --os-version="\u2026"; see `devecocli emulator image list`').option("--force","Overwrite if the tool supports it");no.configureOutput({outputError:(r,e)=>{e(r),/too many arguments/i.test(r)&&e(`
|
|
1217
1217
|
${re("Tip: ")}${Ge("Unquoted --os-version values with spaces/parentheses are split into multiple arguments. Use:")}
|
|
1218
1218
|
${Ye('devecocli emulator create 123 --device-type phone --os-version "HarmonyOS 6.0.1(21)"')}
|
|
1219
1219
|
${Ye('devecocli emulator create 123 --device-type phone --os-version="HarmonyOS 6.0.1(21)"')}
|
|
1220
1220
|
`)}});no.action(async(r,e)=>{try{Rc(r),Oc(e.osVersion);let{manager:t}=await ie(),n=await t.listDownloadedImageOsVersions();Nc(e.osVersion,n),console.log(Ye(`Creating emulator "${r}"...`)),await t.createVirtualDevice({name:r,deviceType:e.deviceType,osVersion:e.osVersion,force:e.force===!0}),console.log(_t(`Emulator "${r}" created successfully.`))}catch(t){console.error(z(`${t.message}`)),process.exit(1)}});we.command("delete <name>").description("Delete a local emulator instance").action(async r=>{let{manager:e}=await ie();console.log(Ye(`Deleting emulator "${r}"...`));try{let t=await e.deleteVirtualDevice(r);console.log(_t(`Emulator "${t}" deleted successfully.`))}catch(t){let n=t;console.error(z(n.message)),n.stdout&&console.error(Ge(n.stdout)),n.stderr&&console.error(Ge(n.stderr)),process.exit(1)}});var ro=we;import{Command as gl}from"commander";import{green as yl,red as wt,cyan as ko,yellow as To,dim as Mo}from"colorette";import vl from"p-limit";import nl from"ora";var Me=class{spinner=null;isRunning=!1;start(e){this.spinner?this.spinner.text=e:this.spinner=nl(e),this.spinner.start(),this.isRunning=!0}stop(){this.spinner&&this.isRunning&&(this.spinner.stop(),this.isRunning=!1)}succeed(e){this.spinner&&(this.spinner.succeed(e),this.isRunning=!1)}fail(e){this.spinner&&(this.spinner.fail(e),this.isRunning=!1)}};import*as so from"fs";import*as ao from"path";import{homedir as il}from"os";import rl from"axios";var ur={HTTP_TIMEOUT_MS:2e4},Bt={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 pr="https://matrix.openharmony.cn",Z={TAGS_API_URL:`${pr}/api/model_base/model/tags?serviceType=skill`,SKILLS_API_URL:`${pr}/api/registry/skill/skills`,SKILL_API_BASE:`${pr}/api/registry/skill`,DEFAULT_PAGE_SIZE:20,SUCCESS_CODE:"20000"},le={"trae-cn":{path:".trae-cn/skills",displayName:"trae-cn"},opencode:{path:".config/opencode/skills",displayName:"opencode"},cursor:{path:".cursor/skills",displayName:"cursor"},codebuddy:{path:".codebuddy/skills",displayName:"codebuddy"},qoder:{path:".qoder/skills",displayName:"qoder"}};import{homedir as Je}from"os";import be from"path";var oe="deveco-mcp";var Se={opencode:{name:"opencode",displayName:"OpenCode",supportsGlobal:!0,globalConfigPath:be.join(Je(),".config","opencode","opencode.json"),projectConfigPath:".opencode/opencode.json",mcpServersKey:"mcp",format:"opencode"},"trae-cn":{name:"trae-cn",displayName:"Trae-CN",supportsGlobal:!0,globalConfigPath:be.join(Je(),".config","trae-cn","mcp.json"),projectConfigPath:".trae/mcp.json",mcpServersKey:"mcpServers",format:"standard"},cursor:{name:"cursor",displayName:"Cursor",supportsGlobal:!0,globalConfigPath:be.join(Je(),".cursor","mcp.json"),projectConfigPath:".cursor/mcp.json",mcpServersKey:"mcpServers",format:"standard"},codebuddy:{name:"codebuddy",displayName:"Codebuddy",supportsGlobal:!0,globalConfigPath:be.join(Je(),".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(Je(),"AppData","Roaming"),"Qoder","SharedClientCache"):be.join(Je(),"Library","Application Support","Qoder","SharedClientCache"),"mcp.json"),projectConfigPath:".mcp.json",mcpServersKey:"mcpServers",format:"standard"}};function io(r){return{type:"local",command:["devecocli","serve","mcp"],environment:{PROJECT_PATH:r??"."},enabled:!0}}function oo(r){return{type:"stdio",command:"devecocli",args:["serve","mcp"],env:{PROJECT_PATH:r??"${workspaceFolder}"}}}function zt(r,e){return r.format==="opencode"?io(e):oo(e)}var hr=class{client;constructor(){let e={timeout:ur.HTTP_TIMEOUT_MS,headers:{"User-Agent":Bt.USER_AGENT,"accept-language":Bt.ACCEPT_LANGUAGE},transformResponse:[t=>t],proxy:!1};this.client=rl.create(e),this.client.interceptors.response.use(t=>t,t=>{let n=`Network connection failed (${t.code}). Please check your proxy configuration or network settings`;throw new Error(`${t.message}
|
|
1221
|
-
${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}},Pe=new hr;async function Vt(){let r=await Pe.get(Z.TAGS_API_URL),t=qt(r,"Tags API").data.skill.filter(n=>n.name==="HMOS"||n.name==="DevEco");if(t.length===0)throw new Error("No HMOS or DevEco tags found");return t.map(n=>n.id)}async function ol(r){let e=[],t=Z.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await Pe.post(Z.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=qt(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function fr(r){let e=new Map,t=r.map(i=>ol(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values())}async function sl(r,e){let t=await Pe.post(Z.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Z.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return qt(t,"Skills API").data.list}async function mr(r,e){let t=new Map,n=e.map(o=>sl(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values())}function co(r){let e=[];for(let[,t]of Object.entries(le)){let n=ao.join(il(),t.path,r);so.existsSync(n)&&e.push(t.displayName)}return e.sort()}function qt(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=Pe.parseJson(r);if(t.code!==Z.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function lo(r){let e=`${Z.SKILL_API_BASE}/${r}/checksum`,t=await Pe.get(e);return qt(t,"Checksum API").data}import al from"adm-zip";import cl from"crypto";import po from"fs";import R from"path";import{fileURLToPath as ll}from"url";import{homedir as ho}from"os";import{red as dl}from"colorette";var de=po.promises;function gr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function uo(r,e){let t=R.resolve(e),n=R.resolve(r),i=R.relative(n,t);if(i.startsWith("..")||R.isAbsolute(i))throw new Error(`Path escape detected: ${e}`)}function yr(r){return R.isAbsolute(r)?r:R.resolve(process.cwd(),r)}function ul(r){return cl.createHash("sha256").update(r).digest("hex")}async function pl(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=ul(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function fo(r){let e=`${Z.SKILL_API_BASE}/${r}/install?format=zip`,t=await Pe.getBinary(e),n=await lo(r);return await pl(t,n),t}async function hl(r,e,t){gr(t);let n=new al(r),i=n.getEntries();try{await de.stat(e)}catch{await de.mkdir(e,{recursive:!0})}let o=R.join(e,t);uo(e,o);for(let s of i){let a=R.join(o,s.entryName);uo(o,a)}n.extractAllTo(o,!0)}async function vr(r){let e=le[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(le).join(", ")}`);let t=R.join(ho(),e.path.replace("/skills",""));try{return await de.access(t),!0}catch{return!1}}function wr(r){let e=le[r];return R.join(ho(),e.path)}function br(r,e){return R.join(r,"."+e,"skills")}async function fl(r,e,t){gr(e);let n=R.join(r,e);try{if(await de.access(n),t)await de.rm(n,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${r}`),{skillDir:n,shouldSkip:!0}}catch{}return{skillDir:n,shouldSkip:!1}}async function Sr(r,e,t){await hl(r,e,t),console.log(`Skill ${t} installed to ${R.join(e,t)}`)}async function Pr(r,e,t){let n=R.join(e,t);await de.mkdir(n,{recursive:!0});let i=R.join(n,R.basename(r));await de.copyFile(r,i),console.log(`Skill ${t} installed to ${n}`)}function mo(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(dl(`Skill ${r} operation failed - ${n}`)),{success:!1,error:n}}async function Ke(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await fl(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return mo(r,i,"Installation failed")}}async function Er(r,e){try{gr(r);let t=await e(),n=R.join(t,r);try{await de.access(n)}catch{return console.log(`Skill ${r} does not exist in ${t}`),{success:!0,skipped:!0}}return await de.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}`),{success:!0}}catch(t){return mo(r,t,"Removal failed")}}async function go(r,e,t,n=!1){return Ke(r,()=>wr(e),i=>Sr(t,i,r),n)}async function yo(r,e,t,n=!1){return Ke(r,()=>t,i=>Sr(e,i,r),n)}async function vo(r,e,t,n,i=!1){return Ke(r,()=>br(t,n),o=>Sr(e,o,r),i)}async function wo(r,e,t,n=!1){return Ke(r,()=>wr(t),i=>Pr(e,i,r),n)}async function bo(r,e,t,n,i=!1){return Ke(r,()=>br(t,n),o=>Pr(e,o,r),i)}async function So(r,e,t,n=!1){return Ke(r,()=>t,i=>Pr(e,i,r),n)}async function Po(r,e){return Er(r,()=>wr(e))}async function Eo(r,e){return Er(r,()=>e)}async function Do(r,e,t){return Er(r,()=>br(e,t))}function Io(){let e=R.dirname(ll(import.meta.url));for(;;){let t=R.join(e,"SKILL.md");if(po.existsSync(t))return t;let n=R.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package; please reinstall deveco-cli.")}import Co from"fs";import{cyan as ml}from"colorette";async function mt(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await vr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function gt(){let r=[];for(let e of Object.keys(le))await vr(e)&&r.push(e);return r}function yt(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(ml("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Ee(r,e,t){if(!Co.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!Co.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function vt(r,e,t){if(r&&(e||t))throw new Error("Cannot use --path with --project or --agent");return{resolvedPath:r?yr(r):void 0,resolvedProject:e?yr(e):void 0}}async function Yt(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await mt(r.agent)).map(a=>({project:t,agent:a})):t?i=(await gt()).map(a=>({project:t,agent:a})):r.agent?n=await mt(r.agent):n=await gt(),!o&&n.length===0&&i.length===0)throw new Error("No agents found. Please install an AI agent (cursor, opencode, etc.) or use --path for a custom location.");return{agents:n,projectAgents:i,customPath:o}}async function wl(r){let e=await Vt();if(r.all)return(await fr(e)).map(n=>n.enName);{let n=(await mr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function bl(r,e,t,n){let i=[];if(t.customPath){let o=await yo(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await go(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await vo(r,e,o,s,n);i.push(a)}return i}function Sl(r){if(r.all&&r.skill)throw new Error("--all and --skill cannot be specified together");if(!r.all&&!r.skill)throw new Error("Must specify --all or --skill");let{resolvedPath:e,resolvedProject:t}=vt(r.path,r.project,r.agent);return t&&Ee(t,"Project directory",r.force),e&&Ee(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function Pl(r,e,t){let n=await Yt(r,e,t);return{skillNames:await wl(r),targets:n}}async function El(r,e,t,n){let i=[],o=r.length,s=vl(5),a=r.map(async c=>s(async()=>{try{let d=await fo(c);return{name:c,buffer:d,success:!0}}catch(d){let u=d instanceof Error?d.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],u=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${u}...`);let b=await a[c];if(!b.success){n.fail(),console.log(wt(`${d}: Download failed - ${b.error}`)),i.push({success:!1});continue}n.stop();let k=await bl(d,b.buffer,e,t);i.push(...k)}return i}async function Dl(r){let e=new Me;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=Sl(r),{skillNames:i,targets:o}=await Pl(r,t,n),s=await El(i,o,r.force||!1,e);e.stop(),yt(s)}catch(t){throw e.stop(),t}}function Il(r){let{resolvedPath:e,resolvedProject:t}=vt(r.path,r.project,r.agent);return t&&Ee(t,"Project directory"),e&&Ee(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Cl(r,e){let t=new Me;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=Il(e);t.stop();let o=await Al(e,r,n,i);t.stop(),yt(o)}catch(n){throw t.stop(),n}}function Ao(r,e=""){if(r.length===0)throw new Error(`No agents found. Please install an AI agent (cursor, opencode, etc.) ${e}`)}async function Gt(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await Po(r,n.agent):await Do(r,n.project,n.agent);t.push(i)}return t}async function Al(r,e,t,n){if(t)return[await Eo(e,t)];if(n&&r.agent){let a=(await mt(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return Gt(e,a)}if(n){let s=await gt();Ao(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return Gt(e,a)}if(r.agent){let a=(await mt(r.agent)).map(c=>({type:"agent",agent:c}));return Gt(e,a)}let i=await gt();Ao(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Gt(e,o)}var bt=new gl("skills").description("Manage HMOS skills");bt.command("list").description("List all available HMOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new Me;try{e.start("Fetching skills...");let t=await Vt(),n=await fr(t);if(n.length===0){e.stop(),console.log(To("No skills available"));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(ko(i.enName)),console.log(Mo(i.description));let o=co(i.enName);o.length>0&&console.log(yl(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(wt(t.message)),process.exit(1)}});bt.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Me;try{e.start("Searching skills...");let t=await Vt(),n=await mr(r,t);if(n.length===0){console.log(To(`No skills found matching '${r}'`)),e.stop();return}e.succeed(`Found ${n.length} skills`);for(let i of n)console.log(ko(i.enName)),console.log(Mo(i.description)),console.log()}catch(t){e.stop(),console.error(wt(t.message)),process.exit(1)}});bt.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); installs to all available agents if omitted").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory to install the skill into").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await Dl(r)}catch(e){console.error(wt(e.message)),process.exit(1)}});bt.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); removes from all available agents if omitted").option("--project <path>","Project root directory to remove the skill from").option("--path <path>","Path to remove the skill from").action(async r=>{try{await Cl(r.skill,r)}catch(e){console.error(wt(e.message)),process.exit(1)}});var xo=bt;import{Command as Tl,InvalidArgumentError as Oo}from"commander";import{cyan as Jt}from"colorette";function xe(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=_e(t);return n==="transient"?new Error(`${e}: device communication channel is not ready yet. Please retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Dr=[800,1500,2500];function kl(r){return new Promise(e=>setTimeout(e,r))}var Kt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name.includes(t))}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1221
|
+
${n}`)})}async get(e,t){let n=await this.client.request({method:"GET",url:e,params:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}async post(e,t){let n=await this.client.request({method:"POST",url:e,data:t?.params,headers:t?.headers,timeout:t?.timeout});return this.convertResponse(n)}convertResponse(e){return{data:typeof e.data=="string"?e.data:JSON.stringify(e.data),statusCode:e.status,headers:e.headers}}parseJson(e){return JSON.parse(e.data)}async getBinary(e,t){let n=await this.client.request({method:"GET",url:e,responseType:"arraybuffer",headers:t?.headers,timeout:t?.timeout});if(n.status!==200)throw new Error(`HTTP ${n.status}`);return Buffer.from(n.data)}},Pe=new hr;async function Vt(){let r=await Pe.get(Z.TAGS_API_URL),t=qt(r,"Tags API").data.skill.filter(n=>n.name==="HMOS"||n.name==="DevEco");if(t.length===0)throw new Error("No HMOS or DevEco tags found");return t.map(n=>n.id)}async function ol(r){let e=[],t=Z.DEFAULT_PAGE_SIZE,n=1;for(;;){let i=await Pe.post(Z.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:n,pageSize:t,tagIds:[r]}}),o=qt(i,"Skills API");if(e.push(...o.data.list),o.data.list.length<t)break;n++}return e}async function mr(r){let e=new Map,t=r.map(i=>ol(i)),n=await Promise.all(t);for(let i of n)for(let o of i)e.has(o.id)||e.set(o.id,o);return Array.from(e.values())}async function sl(r,e){let t=await Pe.post(Z.SKILLS_API_URL,{headers:{"Content-Type":"application/json"},params:{pageNum:1,pageSize:Z.DEFAULT_PAGE_SIZE,keyword:r,tagIds:[e]}});return qt(t,"Skills API").data.list}async function fr(r,e){let t=new Map,n=e.map(o=>sl(r,o)),i=await Promise.all(n);for(let o of i)for(let s of o)t.has(s.id)||t.set(s.id,s);return Array.from(t.values())}function co(r){let e=[];for(let[,t]of Object.entries(le)){let n=ao.join(il(),t.path,r);so.existsSync(n)&&e.push(t.displayName)}return e.sort()}function qt(r,e){if(r.statusCode!==200)throw new Error(`${e} Request failed: HTTP ${r.statusCode}`);let t=Pe.parseJson(r);if(t.code!==Z.SUCCESS_CODE)throw new Error(`${e} Error returned: ${t.code} - ${t.message}`);return t}async function lo(r){let e=`${Z.SKILL_API_BASE}/${r}/checksum`,t=await Pe.get(e);return qt(t,"Checksum API").data}import al from"adm-zip";import cl from"crypto";import po from"fs";import R from"path";import{fileURLToPath as ll}from"url";import{homedir as ho}from"os";import{red as dl}from"colorette";var de=po.promises;function gr(r){if(!/^[A-Za-z0-9._-]+$/.test(r)||r==="."||r==="..")throw new Error(`Unsafe skill name: ${JSON.stringify(r)}`)}function uo(r,e){let t=R.resolve(e),n=R.resolve(r),i=R.relative(n,t);if(i.startsWith("..")||R.isAbsolute(i))throw new Error(`Path escape detected: ${e}`)}function yr(r){return R.isAbsolute(r)?r:R.resolve(process.cwd(),r)}function ul(r){return cl.createHash("sha256").update(r).digest("hex")}async function pl(r,e){if(r.length!==e.size)throw new Error("Skill zip integrity verification failed: Size mismatch");let n=ul(r),i=e.sha256.toLowerCase();if(n!==i)throw new Error("Skill zip integrity verification failed: SHA256 mismatch")}async function mo(r){let e=`${Z.SKILL_API_BASE}/${r}/install?format=zip`,t=await Pe.getBinary(e),n=await lo(r);return await pl(t,n),t}async function hl(r,e,t){gr(t);let n=new al(r),i=n.getEntries();try{await de.stat(e)}catch{await de.mkdir(e,{recursive:!0})}let o=R.join(e,t);uo(e,o);for(let s of i){let a=R.join(o,s.entryName);uo(o,a)}n.extractAllTo(o,!0)}async function vr(r){let e=le[r];if(!e)throw new Error(`Invalid agent: ${r}, Valid options are: ${Object.keys(le).join(", ")}`);let t=R.join(ho(),e.path.replace("/skills",""));try{return await de.access(t),!0}catch{return!1}}function wr(r){let e=le[r];return R.join(ho(),e.path)}function br(r,e){return R.join(r,"."+e,"skills")}async function ml(r,e,t){gr(e);let n=R.join(r,e);try{if(await de.access(n),t)await de.rm(n,{recursive:!0,force:!0});else return console.log(`Skill ${e} exists in ${r}`),{skillDir:n,shouldSkip:!0}}catch{}return{skillDir:n,shouldSkip:!1}}async function Sr(r,e,t){await hl(r,e,t),console.log(`Skill ${t} installed to ${R.join(e,t)}`)}async function Pr(r,e,t){let n=R.join(e,t);await de.mkdir(n,{recursive:!0});let i=R.join(n,R.basename(r));await de.copyFile(r,i),console.log(`Skill ${t} installed to ${n}`)}function fo(r,e,t=""){let n=e instanceof Error?e.message:t;return console.log(dl(`Skill ${r} operation failed - ${n}`)),{success:!1,error:n}}async function Ke(r,e,t,n){try{let i=await e(),{shouldSkip:o}=await ml(i,r,n);return o?{success:!0,skipped:!0}:(await t(i),{success:!0})}catch(i){return fo(r,i,"Installation failed")}}async function Er(r,e){try{gr(r);let t=await e(),n=R.join(t,r);try{await de.access(n)}catch{return console.log(`Skill ${r} does not exist in ${t}`),{success:!0,skipped:!0}}return await de.rm(n,{recursive:!0,force:!0}),console.log(`Skill ${r} removed from ${n}`),{success:!0}}catch(t){return fo(r,t,"Removal failed")}}async function go(r,e,t,n=!1){return Ke(r,()=>wr(e),i=>Sr(t,i,r),n)}async function yo(r,e,t,n=!1){return Ke(r,()=>t,i=>Sr(e,i,r),n)}async function vo(r,e,t,n,i=!1){return Ke(r,()=>br(t,n),o=>Sr(e,o,r),i)}async function wo(r,e,t,n=!1){return Ke(r,()=>wr(t),i=>Pr(e,i,r),n)}async function bo(r,e,t,n,i=!1){return Ke(r,()=>br(t,n),o=>Pr(e,o,r),i)}async function So(r,e,t,n=!1){return Ke(r,()=>t,i=>Pr(e,i,r),n)}async function Po(r,e){return Er(r,()=>wr(e))}async function Eo(r,e){return Er(r,()=>e)}async function Do(r,e,t){return Er(r,()=>br(e,t))}function Io(){let e=R.dirname(ll(import.meta.url));for(;;){let t=R.join(e,"SKILL.md");if(po.existsSync(t))return t;let n=R.dirname(e);if(n===e)break;e=n}throw new Error("SKILL.md not found in deveco-cli package; please reinstall deveco-cli.")}import Co from"fs";import{cyan as fl}from"colorette";async function ft(r){if(!r)return[];let e=[],t=r.split(",").map(n=>n.trim());for(let n of t){if(!await vr(n))throw new Error(`Agent ${n} not found`);e.push(n)}return e}async function gt(){let r=[];for(let e of Object.keys(le))await vr(e)&&r.push(e);return r}function yt(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(fl("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`),n>0&&(process.exitCode=1)}function Ee(r,e,t){if(!Co.existsSync(r)){if(t)return;throw new Error(`${e} "${r}" not found`)}if(!Co.statSync(r).isDirectory())throw new Error(`"${r}" is not a directory`)}function vt(r,e,t){if(r&&(e||t))throw new Error("Cannot use --path with --project or --agent");return{resolvedPath:r?yr(r):void 0,resolvedProject:e?yr(e):void 0}}async function Yt(r,e,t){let n=[],i=[],o;if(e?o=e:t&&r.agent?i=(await ft(r.agent)).map(a=>({project:t,agent:a})):t?i=(await gt()).map(a=>({project:t,agent:a})):r.agent?n=await ft(r.agent):n=await gt(),!o&&n.length===0&&i.length===0)throw new Error("No agents found. Please install an AI agent (cursor, opencode, etc.) or use --path for a custom location.");return{agents:n,projectAgents:i,customPath:o}}async function wl(r){let e=await Vt();if(r.all)return(await mr(e)).map(n=>n.enName);{let n=(await fr(r.skill,e)).find(i=>i.enName===r.skill);if(!n)throw new Error(`Skill "${r.skill}" not found`);return[n.enName]}}async function bl(r,e,t,n){let i=[];if(t.customPath){let o=await yo(r,e,t.customPath,n);return i.push(o),i}for(let o of t.agents){let s=await go(r,o,e,n);i.push(s)}for(let{project:o,agent:s}of t.projectAgents){let a=await vo(r,e,o,s,n);i.push(a)}return i}function Sl(r){if(r.all&&r.skill)throw new Error("--all and --skill cannot be specified together");if(!r.all&&!r.skill)throw new Error("Must specify --all or --skill");let{resolvedPath:e,resolvedProject:t}=vt(r.path,r.project,r.agent);return t&&Ee(t,"Project directory",r.force),e&&Ee(e,"Directory",r.force),{resolvedPath:e,resolvedProject:t}}async function Pl(r,e,t){let n=await Yt(r,e,t);return{skillNames:await wl(r),targets:n}}async function El(r,e,t,n){let i=[],o=r.length,s=vl(5),a=r.map(async c=>s(async()=>{try{let d=await mo(c);return{name:c,buffer:d,success:!0}}catch(d){let u=d instanceof Error?d.message:"unknown error";return{name:c,error:u,success:!1}}}));for(let c=0;c<r.length;c++){let d=r[c],u=o>1?` (${c+1}/${o})`:"";n.start(`Installing ${d}${u}...`);let b=await a[c];if(!b.success){n.fail(),console.log(wt(`${d}: Download failed - ${b.error}`)),i.push({success:!1});continue}n.stop();let k=await bl(d,b.buffer,e,t);i.push(...k)}return i}async function Dl(r){let e=new Me;try{e.start("Installing skill...");let{resolvedPath:t,resolvedProject:n}=Sl(r),{skillNames:i,targets:o}=await Pl(r,t,n),s=await El(i,o,r.force||!1,e);e.stop(),yt(s)}catch(t){throw e.stop(),t}}function Il(r){let{resolvedPath:e,resolvedProject:t}=vt(r.path,r.project,r.agent);return t&&Ee(t,"Project directory"),e&&Ee(e,"Directory"),{resolvedPath:e,resolvedProject:t}}async function Cl(r,e){let t=new Me;try{t.start("Removing skill...");let{resolvedPath:n,resolvedProject:i}=Il(e);t.stop();let o=await Al(e,r,n,i);t.stop(),yt(o)}catch(n){throw t.stop(),n}}function Ao(r,e=""){if(r.length===0)throw new Error(`No agents found. Please install an AI agent (cursor, opencode, etc.) ${e}`)}async function Gt(r,e){let t=[];for(let n of e){let i=n.type==="agent"?await Po(r,n.agent):await Do(r,n.project,n.agent);t.push(i)}return t}async function Al(r,e,t,n){if(t)return[await Eo(e,t)];if(n&&r.agent){let a=(await ft(r.agent)).map(c=>({type:"projectAgent",agent:c,project:n}));return Gt(e,a)}if(n){let s=await gt();Ao(s);let a=s.map(c=>({type:"projectAgent",agent:c,project:n}));return Gt(e,a)}if(r.agent){let a=(await ft(r.agent)).map(c=>({type:"agent",agent:c}));return Gt(e,a)}let i=await gt();Ao(i,"or use --path for a custom location.");let o=i.map(s=>({type:"agent",agent:s}));return Gt(e,o)}var bt=new gl("skills").description("Manage HMOS skills");bt.command("list").description("List all available HMOS skills").option("-l, --long","Show detailed information including description and installation status").action(async r=>{let e=new Me;try{e.start("Fetching skills...");let t=await Vt(),n=await mr(t);if(n.length===0){e.stop(),console.log(To("No skills available"));return}e.succeed(`Fetched ${n.length} skills`);for(let i of n)if(r.long){console.log(ko(i.enName)),console.log(Mo(i.description));let o=co(i.enName);o.length>0&&console.log(yl(`Installed for: ${o.join(", ")}`)),console.log()}else console.log(i.enName)}catch(t){e.stop(),console.error(wt(t.message)),process.exit(1)}});bt.command("find <keyword>").description("Search skills by keyword").action(async r=>{let e=new Me;try{e.start("Searching skills...");let t=await Vt(),n=await fr(r,t);if(n.length===0){console.log(To(`No skills found matching '${r}'`)),e.stop();return}e.succeed(`Found ${n.length} skills`);for(let i of n)console.log(ko(i.enName)),console.log(Mo(i.description)),console.log()}catch(t){e.stop(),console.error(wt(t.message)),process.exit(1)}});bt.command("add").description("Install skills to AI agents").option("--all","Install all available skills").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); installs to all available agents if omitted").option("--skill <skill-name>","Name of the skill to install").option("-f, --force","Overwrite an existing skill installation").option("--project <path>","Project root directory to install the skill into").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").action(async r=>{try{await Dl(r)}catch(e){console.error(wt(e.message)),process.exit(1)}});bt.command("remove").description("Remove an installed skill from AI agents").requiredOption("--skill <skill-name>","Name of the skill to remove").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); removes from all available agents if omitted").option("--project <path>","Project root directory to remove the skill from").option("--path <path>","Path to remove the skill from").action(async r=>{try{await Cl(r.skill,r)}catch(e){console.error(wt(e.message)),process.exit(1)}});var xo=bt;import{Command as Tl,InvalidArgumentError as Oo}from"commander";import{cyan as Jt}from"colorette";function xe(r,e){if(r.exitCode===0)return null;let t=r.stderr||r.stdout,n=_e(t);return n==="transient"?new Error(`${e}: device communication channel is not ready yet. Please retry in a few seconds.`):n==="fatal"?new Error(`${e}: ${t.trim()}`):null}var Dr=[800,1500,2500];function kl(r){return new Promise(e=>setTimeout(e,r))}var Kt=class{toolProvider;deviceManager;constructor(e){this.toolProvider=e,this.deviceManager=B.from(e)}createFollowLineHandler(e){return(t,n)=>{let i=e.keyword?t.filter(o=>o.includes(e.keyword)):t;if(n!=="stderr")for(let o of i)console.log(o)}}findDeviceByArg(e,t){return e.find(n=>n.serial===t||n.name.includes(t))}formatConnectedDeviceList(e){return e.map(t=>` - ${t.name} (${t.serial})`).join(`
|
|
1222
1222
|
`)}async loadConnectedDevicesByName(){let e=await this.getConnectedDevices();if(e)return e}async selectDevice(e){let t=await this.getConnectedDeviceSerials();if(!t)return;if(!e&&t.length===1){let i=t[0];return w(Jt(`Using device serial: ${i}`)),i}if(e&&t.includes(e))return w(Jt(`Using device serial: ${e}`)),e;let n=await this.loadConnectedDevicesByName();if(n){if(e){let i=this.findDeviceByArg(n,e);if(i)return w(Jt(`Using device: ${i.name} (${i.serial})`)),i.serial;let o=this.formatConnectedDeviceList(n);throw new Error(`Device '${e}' not found.
|
|
1223
1223
|
Available devices:
|
|
1224
1224
|
${o}`)}if(n.length===1){let i=n[0];return w(Jt(`Using device: ${i.name} (${i.serial})`)),i.serial}throw new Error("Multiple devices found. Please specify a target device using `--device <name>` or `--device <serial>`.\nAvailable devices:\n"+this.formatConnectedDeviceList(n))}}async getConnectedDeviceSerials(){let e=await this.deviceManager.listDevices();if(e.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");return e.map(t=>t.serial)}async getConnectedDevices(){let e=await this.deviceManager.listDevicesWithName();if(e.length===0)throw new Error("No active devices found. Please start an emulator or connect a physical device.");return e}async getPidForBundle(e,t,n){w(`Trying to get PID for bundle: ${n}`),E.assertBundleName(n);let i=await ye(e,["-t",t,"shell","pidof",n]),o=xe(i,"Failed to look up PID");if(o)throw o;if(i.exitCode===0&&i.stdout.trim()){let s=i.stdout.trim(),a=s.split(/\s+/)[0]||s;return w(`Found PID for ${n}: ${a}`),a}return w(`No PID found for bundle: ${n}`),null}async resizeHilogBuffer(e,t,n){w(`Setting hilog buffer size to: ${n}`);let i=await ye(e,["-t",t,"shell","hilog","-G",n]),o=xe(i,"Failed to resize hilog buffer");if(o)throw o;i.exitCode!==0&&console.error(`Failed to resize hilog buffer: ${i.stderr||i.stdout}`)}buildHilogCommand(e,t,n,i){let o=this.buildHilogShellCommand(n,i);return[e,["-t",t,"shell",o]]}buildHilogShellCommand(e,t){let n=["hilog"];return e.isFollow||n.push("-x"),e.tag&&(E.assertHilogToken(e.tag,"tag"),n.push("-T",e.tag)),e.level&&(E.assertHilogLevel(e.level),n.push("-L",e.level)),e.domain&&(E.assertHilogToken(e.domain,"domain"),n.push("-D",e.domain)),t&&n.push("-P",t),e.keyword&&(E.assertHilogKeyword(e.keyword),n.push("-e",E.quotePosixShellArg(e.keyword))),n.join(" ")}async followHilog(e,t,n,i,o){let a=await gi(e,t,{onData:n,onError:i,onClose:o});return{stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode}}async runHilogWithSpawnRetry(e,t,n,i,o){let s=1+Dr.length,a={stdout:"",stderr:"",exitCode:-1};for(let c=0;c<s;c++){a=await this.followHilog(e,t,n,i,o);let d=a.exitCode===0?a.stdout:a.stderr||a.stdout;if(_e(d)!=="transient"||c>=s-1)return a;w(`hdc transient failure on \`${t.join(" ")}\`: retrying in ${Dr[c]}ms`),await kl(Dr[c])}return a}async printTailSnapshotIfNeeded(e,t,n,i){if(!n.tail&&!n.fromSeconds&&!n.toSeconds)return;let o={...n,isFollow:!1},[,s]=this.buildHilogCommand(e,t,o,i),a=await ye(e,s),c=xe(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let d=E.filterLogsByRelativeWindow(a.stdout||a.stderr,n.fromSeconds,n.toSeconds);d=E.getLastLines(d,n.tail),d.trim()&&console.log(d)}async getHilogOnce(e,t,n,i){let[o,s]=this.buildHilogCommand(e,t,n,i);w(`Ready to execute hilog command: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,()=>{},b=>{w(`hilog once stream error callback: ${b.message}`)},()=>{}),c=xe(a,"Failed to get hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to get hilog: ${a.stderr}`);let d=a.stdout||a.stderr,u=E.filterLogsByRelativeWindow(d,n.fromSeconds,n.toSeconds);return u=E.getLastLines(u,n.tail),u}async runHilogFollow(e,t,n,i){await this.printTailSnapshotIfNeeded(e,t,n,i);let[o,s]=this.buildHilogCommand(e,t,n,i);w(`Ready to execute hilog command which contain follow and tail: ${o} ${s.join(" ")}`);let a=await this.runHilogWithSpawnRetry(o,s,this.createFollowLineHandler(n),d=>{console.error(d.message)},()=>{}),c=xe(a,"Failed to follow hilog");if(c)throw c;if(a.exitCode!==0&&a.stderr)throw new Error(`Failed to follow hilog: ${a.stderr}`);return""}async getHilog(e,t){let n=this.toolProvider.hdcPath,i=t.bundleName?await this.getPidForBundle(n,e,t.bundleName):void 0;if(t.bundleName&&!i)throw new Error(`No running process found for bundle '${t.bundleName}'. Make sure the app is launched on the device before fetching logs.`);return t.logSize&&await this.resizeHilogBuffer(n,e,t.logSize),t.isFollow?await this.runHilogFollow(n,e,t,i||""):await this.getHilogOnce(n,e,t,i||"")}async getCrashLog(e,t){w(`Fetching crash logs from device: ${e}`);let n=this.toolProvider.hdcPath,i=await this.listCrashLogs(n,e,t);if(i.length===0)return t?`No crash logs found for bundle '${t}'.`:"No crash logs found.";let s=[...i].sort((c,d)=>{let u=c.split("-").pop()||"";return(d.split("-").pop()||"").localeCompare(u)})[0],a=await this.fetchCrashLogContent(n,e,s);return`--- Latest Crash Log File: ${s} ---${a}`}async listCrashLogs(e,t,n){let i=["-t",t,"shell","hidumper","-s","1201","-a","-p Faultlogger"];w(`Executing command: ${e} ${i.join(" ")}`);let o=await ye(e,i),s=xe(o,"Failed to list crash logs");if(s)throw s;if(o.exitCode!==0)throw new Error(`Failed to list crash logs: ${o.stderr||o.stdout}`);return w(`Crash logs list output:
|
|
1225
1225
|
${o.stdout}`),o.stdout.split(`
|
|
1226
1226
|
`).map(c=>c.trim()).filter(c=>c.length>0).filter(c=>{try{return E.assertCrashFilename(c),!0}catch{return!1}}).filter(c=>n?c.toLowerCase().includes(n.toLowerCase()):!0)}async fetchCrashLogContent(e,t,n){w(`Fetching latest crash log file: ${n}`);let i=["-t",t,"shell","hidumper","-s","1201","-a",`-p Faultlogger -f ${n}`];w(`Executing command: ${e} ${i.join(" ")}`);let o=await ye(e,i),s=xe(o,"Failed to fetch crash log content");if(s)throw s;return o.exitCode!==0&&o.stderr&&console.error(`Warning: Failed to fetch crash log content: ${o.stderr}`),o.stdout+o.stderr}};import{cyan as Ir,red as No}from"colorette";import Ml from"ora";function xl(r){try{return E.parsePositiveInteger(r,"tail")}catch{throw new Oo("tail must be a positive integer")}}function Ro(r,e){try{return E.parseDurationToSeconds(r,e)}catch{throw new Oo(`${e} must be like 30s, 5m or 2.5m (s/m only; seconds/default must be integers)`)}}function Rl(r){if(r.to&&r.follow)throw new Error("--to cannot be used with --follow");E.assertRelativeTimeRange(r.from,r.to)}async function Ol(r,e,t,n,i){return t.crash?await r.getCrashLog(e,t.bundleName):await r.getHilog(e,{level:t.level,bundleName:t.bundleName,keyword:t.keyword,isFollow:!!t.follow,tail:t.tail,fromSeconds:n,toSeconds:i})}function Nl(r,e,t,n){let i=E.filterLogsByRelativeWindow(r,t,n);return e.tail?E.getLastLines(i,e.tail):i}var Ll=new Tl("log").description("Obtain device application logs").configureOutput({outputError:(r,e)=>e(No(r))}).option("--device <device>","Target device (name or serial)").option("--crash","Only obtain the crash log").option("--level <level>","Log level filter: D, I, W, E, F").option("--bundle-name <bundle-name>","Filter by application bundle name").option("--keyword <keyword>","Keyword filter").option("--tail <num>","Show only the latest N log lines",xl).option("--from <start>","Start offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Ro(r,"from")).option("--to <end>","End offset from now, e.g. 30s, 5m, 2.5m, or 120",r=>Ro(r,"to")).option("--follow","Follow the log stream in real-time.").action(async r=>{await Hl(r)});async function Hl(r){let e=Ml({text:"Preparing log request\u2026",color:"cyan"}),t=()=>{e.stop(),e.clear()};try{e.start(),Rl(r);let n=r.from,i=r.to,o=await N.new(),s=new Kt(o),a=await s.selectDevice(r.device);a||(t(),process.exit(1)),w(Ir(`deviceId: ${a}`)),w(Ir(`type: ${r.crash?"Crash logs":"Common logs"}`)),w(Ir("Obtaining logs ...")),e.text="Fetching logs\u2026",r.follow&&t();let c=await Ol(s,a,r,n,i);t(),r.crash&&c&&(c=Nl(c,r,n,i)),c&&console.log(c)}catch(n){t(),console.error(No(n.message)),process.exit(1)}}var Lo=Ll;import Pt from"path";import ue from"fs";import Ar from"process";import Bo from"os";import{Command as Gl}from"commander";import{green as $o,red as Cr,cyan as Jl,yellow as _o}from"colorette";import j from"fs-extra";import T from"path";import*as Ho from"os";import{fileURLToPath as jl}from"url";var Fl={17:{sdkVersion:"5.0.5(17)",modelVersion:"5.0.5"},18:{sdkVersion:"5.1.0(18)",modelVersion:"5.1.0"},19:{sdkVersion:"5.1.1(19)",modelVersion:"5.1.1"},20:{sdkVersion:"6.0.0(20)",modelVersion:"6.0.0"},21:{sdkVersion:"6.0.1(21)",modelVersion:"6.0.1"},22:{sdkVersion:"6.0.2(22)",modelVersion:"6.0.2"},23:{sdkVersion:"6.1.0(23)",modelVersion:"6.1.0"},24:{sdkVersion:"6.1.1(24)",modelVersion:"6.1.1"}},$l=["build-profile.json5","AppScope/resources/base/media/layered_image.json","entry/src/main/resources/base/media/layered_image.json"];function _l(){let r=import.meta.url,e=jl(r);if(e.includes("dist")){let o=T.dirname(e),s=T.dirname(o);return T.join(s,"templates","application")}let t=T.dirname(e),n=T.dirname(t),i=T.dirname(n);return T.join(i,"templates","application")}function jo(r,e){j.mkdirSync(e,{recursive:!0});for(let t of j.readdirSync(r,{withFileTypes:!0})){let n=T.join(r,t.name),i=T.join(e,t.name);if(t.isDirectory()){jo(n,i);continue}j.existsSync(i)||(j.mkdirSync(T.dirname(i),{recursive:!0}),j.copyFileSync(n,i))}}function St(r,e){let t=j.readFileSync(r,"utf-8"),n=t;for(let[i,o]of e)n=n.replaceAll(i,o);n!==t&&j.writeFileSync(r,n,"utf-8")}function Wl(r,e){if(e===22)return;let t=Fl[e];t&&(St(T.join(r,"build-profile.json5"),[["6.0.2(22)",t.sdkVersion]]),St(T.join(r,"hvigor","hvigor-config.json5"),[["6.0.2",t.modelVersion]]),St(T.join(r,"oh-package.json5"),[["6.0.2",t.modelVersion]]))}function Ul(r){return $l.filter(t=>!j.existsSync(T.join(r,t))).length===0}function Bl(){return Buffer.from([137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,1,0,0,0,1,8,2,0,0,0,144,119,83,222,0,0,0,12,73,68,65,84,8,215,99,248,255,255,255,0,5,254,2,254,0,0,0,0,73,69,78,68,174,66,96,130])}function zl(r){return Ho.platform()==="darwin"?T.join(r,"Contents","plugins","codegenie-plugin","previewProjectTemplate"):T.join(r,"plugins","codegenie-plugin","previewProjectTemplate")}function Vl(r,e){let t=zl(e);if(!j.existsSync(t))return!1;let n=[["AppScope/resources/base/media/background.png","AppScope/resources/base/media/background.png"],["AppScope/resources/base/media/foreground.png","AppScope/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/background.png"],["entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/foreground.png"],["entry/src/main/resources/base/media/startIcon.png","entry/src/main/resources/base/media/startIcon.png"]];for(let[i,o]of n){let s=T.join(t,i),a=T.join(r,o);j.existsSync(s)&&(j.mkdirSync(T.dirname(a),{recursive:!0}),j.copyFileSync(s,a))}return!0}function ql(r){let e=Bl(),t=["AppScope/resources/base/media/background.png","AppScope/resources/base/media/foreground.png","entry/src/main/resources/base/media/background.png","entry/src/main/resources/base/media/foreground.png","entry/src/main/resources/base/media/startIcon.png"];for(let n of t){let i=T.join(r,n);j.mkdirSync(T.dirname(i),{recursive:!0}),j.writeFileSync(i,e)}}function Yl(r,e){e&&Vl(r,e)||ql(r)}function Fo(r,e,t,n,i){let o=_l();if(!j.existsSync(o))throw new Error(`Template directory not found: ${o}`);j.mkdirSync(r,{recursive:!0}),jo(o,r),Yl(r,i),St(T.join(r,"AppScope","resources","base","element","string.json"),[["MyApplication",e]]),St(T.join(r,"AppScope","app.json5"),[["com.example.myapplication",t]]),Wl(r,n);let s=Ul(r);if(!s)throw new Error("Template integrity check failed");return{projectRoot:r,appName:e,bundleName:t,apiLevel:n,verified:s}}function Kl(r){if(r.length<1||r.length>200)throw new Error(`App name length must be 1-200 characters. Current: ${r.length}`);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(r))throw new Error("App name must start with a letter (a-z, A-Z) and contain only letters, digits, and underscores")}function Xl(r){if(r.length<7||r.length>128)throw new Error(`Bundle name length must be 7-128 characters. Current: ${r.length}`);if(r.includes(".."))throw new Error('Bundle name cannot contain consecutive dots (e.g., "com..example")');let e=r.split(".");if(e.length<3)throw new Error("Bundle name must contain at least 3 segments separated by dots");let t=/^[a-zA-Z0-9_]+$/;for(let n=0;n<e.length;n++){let i=e[n];if(!t.test(i))throw new Error(`Segment "${i}" contains invalid characters. Only letters, digits, and underscores allowed`);if(n===0){if(!/^[a-zA-Z]/.test(i))throw new Error(`First segment "${i}" must start with a letter (a-z, A-Z)`)}else if(!/^[a-zA-Z0-9]/.test(i))throw new Error(`Segment "${i}" must start with a letter or digit`);if(!/[a-zA-Z0-9]$/.test(i))throw new Error(`Segment "${i}" must end with a letter or digit`)}}function zo(r){if(Bo.platform()==="win32"){let t=r.replace(/\\/g,"/");return t=t.replace(/\/+/g,"/"),t}return r.replace(/\/+/g,"/")}function Wo(r){if(r.length===0)throw new Error("Project path cannot be empty");if(r.length>120)throw new Error(`Project path cannot exceed 120 characters (current: ${r.length})`);let e=Bo.platform();if(!(e==="win32"?/^[a-zA-Z0-9._\-:\\/]+$/:/^[a-zA-Z0-9._\-/]+$/).test(r)){let o=e==="win32"?"letters, digits, dots, underscores, hyphens, colons, slashes (/) or backslashes (\\)":"letters, digits, dots, underscores, hyphens or slashes (/)";throw new Error(`Project path can only contain ${o}`)}let n=zo(r);if(/[\u4e00-\u9fff]/.test(n))throw new Error("Project path cannot contain Chinese characters");if(n.endsWith("."))throw new Error("Project path cannot end with a dot (.)")}function Zl(r){let e=r,t=Pt.parse(r).root;for(;e!==t;){if(ue.existsSync(e))return e;e=Pt.dirname(e)}return ue.existsSync(t)?t:null}function Uo(r){let e=Zl(r);if(!e)throw new Error(`No existing parent directory found for '${r}'. Cannot create project directory.`);try{ue.accessSync(e,ue.constants.W_OK)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}let t=Pt.join(e,`.deveco_write_test_${Date.now()}`);try{ue.writeFileSync(t,"test"),ue.unlinkSync(t)}catch{throw new Error(`No write permission for directory '${e}'. Cannot create project here.`)}}function Ql(r){return`com.example.${r.toLowerCase()}`}function ed(r,e){if(e){let i=zo(e),o=Pt.resolve(i);if(ue.existsSync(o)){if(ue.readdirSync(o).length>0)throw new Error(`Directory '${o}' is not empty. Cannot create project in non-empty directory.`)}else Uo(o);return o}let t=Ar.cwd(),n=Pt.join(t,r);if(ue.existsSync(n))throw new Error(`Directory '${n}' already exists. Cannot create project here.`);return Uo(n),n}function td(r,e){let t=e?.getMaxApiLevel(),n=23;if(r.apiLevel){let i=Number(r.apiLevel);if(!Number.isInteger(i)||i<17)throw new Error(`Invalid API level ${r.apiLevel}. Minimum supported is API 17`);if(t!==void 0){if(i>t)throw new Error(`Invalid API level ${r.apiLevel}. Your SDK supports API 17-${t}`)}else if(i>n)throw new Error(`Invalid API level ${r.apiLevel}. Without DevEco Studio, supported range is API 17-${n}`);return i}return t!==void 0?t:23}async function nd(){try{return await N.new()}catch(r){console.error(_o(`DevEco Studio not found: ${r.message}`)),console.log(_o("Using placeholder API level instead."));return}}var rd=new Gl("create").description("Scaffold a new HarmonyOS application project").option("--project-path <path>","Project directory path (default: ./<app-name>)").option("--app-name <name>","Application name").option("--bundle-name <bundle>","Bundle name (auto-derived as com.example.<app-name> if omitted)").option("--api-level <level>","API level (auto-detected from SDK if omitted; minimum: 17)").action(async r=>{try{r.appName||(console.error(Cr("Error: --app-name is required")),Ar.exit(1));let e=r.appName;Kl(e);let t=r.bundleName||Ql(e);Xl(t),r.projectPath&&Wo(r.projectPath);let n=ed(e,r.projectPath);Wo(n),console.log(Jl("Initializing project...")),console.log(`Project path: ${n}`),console.log(`App name: ${e}`),console.log(`Bundle name: ${t}`);let i=await nd(),o=td(r,i);console.log(`API level: ${o}`);let s=i?.devecoStudioPath,a=Fo(n,e,t,o,s);console.log(`
|
|
1227
1227
|
`+$o("Project created successfully!")),console.log(`Project root: ${a.projectRoot}`),console.log(`App name: ${a.appName}`),console.log(`Bundle name: ${a.bundleName}`),console.log(`API level: ${a.apiLevel}`),console.log($o("Template integrity check passed"))}catch(e){let t=e;console.error(Cr(`
|
|
1228
|
-
Failed to create project`)),console.error(Cr(t.message)),Ar.exit(1)}}),Vo=rd;import{Command as sd}from"commander";import{red as ad,cyan as Zo}from"colorette";import id from"fs";import kr from"path";import{cyan as od}from"colorette";var Tr=id.promises;async function qo(r){try{let e=await Tr.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read config file ${r}: ${e.message}`,{cause:e})}}async function Yo(r,e){let t=kr.dirname(r);await Tr.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Tr.writeFile(r,n,"utf8")}function Go(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function Jo(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function Ko(r,e,t=!1){let n=Se[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Se).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await qo(n.globalConfigPath);if(Go(i,n.mcpServersKey,oe)&&!t)return console.log(`MCP server ${oe} already configured in ${n.globalConfigPath}`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=zt(n,void 0);return Jo(i,n.mcpServersKey,oe,o,t),await Yo(n.globalConfigPath,i),console.log(`MCP server ${oe} configured in ${n.globalConfigPath}`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Mr(r,e,t=!1){let n=Se[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Se).join(", ")}`};let i=kr.isAbsolute(n.projectConfigPath)?n.projectConfigPath:kr.join(e,n.projectConfigPath);try{let o=await qo(i);if(Go(o,n.mcpServersKey,oe)&&!t)return console.log(`MCP server ${oe} already configured in ${i}`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=zt(n,e);return Jo(o,n.mcpServersKey,oe,s,t),await Yo(i,o),console.log(`MCP server ${oe} configured in ${i}`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function Xo(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(od("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var xr="deveco-cli";async function cd(r,e,t){let n=[];if(r.customPath){let i=await So(xr,e,r.customPath,t.force);return n.push(i),n}for(let{project:i,agent:o}of r.projectAgents){let s=await bo(xr,e,i,o,t.force);n.push(s)}for(let i of r.agents){let o=await wo(xr,e,i,t.force);n.push(o)}return n}async function ld(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Mr(o,i,t);n.push(s)}for(let i of r.agents){let o=await Mr(i,e,t);n.push(o)}return n}async function dd(r,e){let t=[];for(let n of r){if(!Se[n])continue;let o=await Ko(n,process.cwd(),e);t.push(o)}return t}async function ud(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other agents (opencode, trae-cn, cursor, codebuddy).");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await ld(s,e,n):await dd(s.agents,n);a.length>0&&(console.log(Zo("MCP Configuration:")),Xo(a))}async function pd(r){if(r.skill&&r.mcp)throw new Error("Cannot use --skill and --mcp together. Use --skill for skill installation only, or --mcp for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=vt(r.path,r.project,r.agent);t&&Ee(t,"Project directory",r.force),e&&Ee(e,"Directory",r.force);let n=await Yt(r,e,t);if(r.mcp){await ud(n,t,r);return}let i=Io(),o=await cd(n,i,r);console.log(),o.length>0&&(console.log(Zo("Skill Installation:")),yt(o))}var hd=new sd("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); installs to all available agents if omitted").option("--project <path>","Project root directory to install the skill or MCP config into").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite an existing skill / MCP configuration").action(async r=>{try{await pd(r)}catch(e){console.error(ad(e.message)),process.exit(1)}}),Qo=hd;import{Command as Tu}from"commander";import{McpServer as Cu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Au}from"@modelcontextprotocol/sdk/server/stdio.js";import*as lt from"path";import{z as Kr}from"zod";var Xt=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:n}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>n(i)))}};function Rr(){return new Xt}import*as ge from"fs";import*as ee from"path";import{z as Yr}from"zod";import D from"fs";import*as Zt from"os";import*as S from"path";import fd from"json5";var Or="Huawei";var md=3,rs=3,es="DevEco Studio",is={DevEcoStudio:"deveco_studio"};function Nr(r){if(!D.existsSync(r)||!D.statSync(r).isDirectory())return!1;let e=D.existsSync(S.join(r,"build-profile.json5")),t=D.existsSync(S.join(r,"hvigorfile.js"))||D.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=D.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return fd.parse(n).app!==void 0}catch{return!1}}function os(r,e,t){if(e>=t)return null;let n=gd(r),i=yd(n);if(i)return i;for(let o of n){let s=os(o,e+1,t);if(s)return s}return null}function gd(r){try{let e=D.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function yd(r){for(let e of r)if(Nr(e))return e;return null}function pe(r){if(!r||r.trim()==="")return null;let e=S.resolve(r),t;try{t=D.realpathSync(e)}catch{t=e}if(!D.existsSync(t))return null;if(Nr(t))return t;let n=t;for(let i=1;i<=3;i++){let o=S.dirname(n);if(o===n)break;if(Nr(o))return o;n=o}if(D.statSync(t).isDirectory()){let i=os(t,0,md);if(i)return i}return null}function ss(r){if(process.platform==="linux")return null;let e=r??Re();if(!e)return null;let t;if(process.platform==="win32")t=S.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=S.join(e,"contents","plugins","openharmony");else return null;let n=S.join(t,"ace-server","out","index.js");return D.existsSync(n)?t:null}var vd=["sdk","default","openharmony","native","llvm","bin","clangd"],Lr=[".idea",".deveco","cxx","compile_commands.json"];function wd(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function ts(r){let e=new Set,t=[r,wd(r)];for(let n of t){let i=S.join(n,...vd);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function as(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of ts(t.trim()))if(e.push(i),D.existsSync(i))return i}let n=r??Re();if(n){for(let i of ts(n))if(e.push(i),D.existsSync(i))return i}return null}function Qt(r){return S.join(r,...Lr)}function Re(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",Or,es),S.join("C:\\Program Files (x86)",Or,es)];return ns(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return ns(r)}return null}function ns(r){for(let e of r)if(D.existsSync(e))return e;return null}function se(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function bd(r){if(!r||!D.existsSync(r)||!cs(r))return!1;let e=se(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>D.existsSync(n))}function cs(r){try{return D.statSync(r).isDirectory()}catch{return!1}}function Hr(r,e){return!r||!D.existsSync(r)?!1:e===is.DevEcoStudio?bd(r):!1}function en(r,e=is.DevEcoStudio){if(!r)return"";if(Hr(r,e))return r;let t=Sd(r,e);if(t)return t;let n=Pd(r,e);return n||r}function Sd(r,e){let t=r;for(let n=0;n<rs;n++){let i=S.dirname(t);if(!i||i===t)break;if(Hr(i,e))return i;t=i}return null}function Pd(r,e){if(!D.existsSync(r)||!cs(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=rs)continue;let o=Ed(n,i,e,t);if(o)return o}return null}function Ed(r,e,t,n){let i;try{i=D.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(Hr(s,t))return s;n.push({p:s,depth:e+1})}return null}function ls(r){return new Promise(e=>setTimeout(e,r))}var Dd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function tn(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&Dd.has(e)}function ds(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ae(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function jr(r){return ae(r)}function Oe(r){let e=jr(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Et(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Oe(t)}}catch{}return r}function us(r){let e=[],t=r.lastIndexOf("file:/");if(t>=0){let n=r.slice(t).replace(/^file:\/+/,"");if(n){let i=n.startsWith("/")?`file://${n}`:`file:///${n}`,o=Et(i);o!==r&&o!==Et(r)&&e.push(o)}}return e}function nn(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(Zt.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(Zt.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(Zt.homedir(),".local","share","devecocli-mcp-server","logs")}function ps(r,e){let t=Id(e),n=Cd(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Ad(t,r,s);return kd(e,a),i}function Id(r){let e;try{e=D.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Cd(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(n+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Ad(r,e,t){let n=!1,i=r.map(o=>{if(n)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):o});return n||i.push(t),i}function kd(r,e){try{D.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{D.writeFileSync(r,e.join(`
|
|
1228
|
+
Failed to create project`)),console.error(Cr(t.message)),Ar.exit(1)}}),Vo=rd;import{Command as sd}from"commander";import{red as ad,cyan as Zo}from"colorette";import id from"fs";import kr from"path";import{cyan as od}from"colorette";var Tr=id.promises;async function qo(r){try{let e=await Tr.readFile(r,"utf8");return e.trim()===""?{}:JSON.parse(e)}catch(e){if(e.code==="ENOENT")return{};throw new Error(`Failed to read config file ${r}: ${e.message}`,{cause:e})}}async function Yo(r,e){let t=kr.dirname(r);await Tr.mkdir(t,{recursive:!0});let n=JSON.stringify(e,null,2);await Tr.writeFile(r,n,"utf8")}function Go(r,e,t){let n=r[e];return!n||typeof n!="object"?!1:t in n}function Jo(r,e,t,n,i){(!r[e]||typeof r[e]!="object")&&(r[e]={});let o=r[e];return t in o&&!i?!1:(o[t]=n,!0)}async function Ko(r,e,t=!1){let n=Se[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Se).join(", ")}`};if(!n.supportsGlobal)return{success:!1,error:`${n.displayName} does not support global MCP configuration. Use --project to configure project-level MCP.`};try{let i=await qo(n.globalConfigPath);if(Go(i,n.mcpServersKey,oe)&&!t)return console.log(`MCP server ${oe} already configured in ${n.globalConfigPath}`),{success:!0,skipped:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"};let o=zt(n,void 0);return Jo(i,n.mcpServersKey,oe,o,t),await Yo(n.globalConfigPath,i),console.log(`MCP server ${oe} configured in ${n.globalConfigPath}`),{success:!0,configPath:n.globalConfigPath,agentName:r,installType:"global"}}catch(i){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${i.message}`}}}async function Mr(r,e,t=!1){let n=Se[r];if(!n)return{success:!1,error:`Unknown agent: ${r}. Supported agents: ${Object.keys(Se).join(", ")}`};let i=kr.isAbsolute(n.projectConfigPath)?n.projectConfigPath:kr.join(e,n.projectConfigPath);try{let o=await qo(i);if(Go(o,n.mcpServersKey,oe)&&!t)return console.log(`MCP server ${oe} already configured in ${i}`),{success:!0,skipped:!0,configPath:i,agentName:r,installType:"project"};let s=zt(n,e);return Jo(o,n.mcpServersKey,oe,s,t),await Yo(i,o),console.log(`MCP server ${oe} configured in ${i}`),{success:!0,configPath:i,agentName:r,installType:"project"}}catch(o){return{success:!1,error:`Failed to configure MCP for ${n.displayName}: ${o.message}`}}}function Xo(r){let e=r.filter(i=>i.success&&!i.skipped).length,t=r.filter(i=>i.skipped).length,n=r.filter(i=>!i.success).length;console.log(),console.log(od("Finished:")),console.log(` Success: ${e}`),console.log(` Skipped: ${t}`),console.log(` Failed: ${n}`);for(let i of r)!i.success&&i.error&&console.error(` - ${i.agentName??"unknown"}: ${i.error}`);n>0&&(process.exitCode=1)}var xr="deveco-cli";async function cd(r,e,t){let n=[];if(r.customPath){let i=await So(xr,e,r.customPath,t.force);return n.push(i),n}for(let{project:i,agent:o}of r.projectAgents){let s=await bo(xr,e,i,o,t.force);n.push(s)}for(let i of r.agents){let o=await wo(xr,e,i,t.force);n.push(o)}return n}async function ld(r,e,t){let n=[];for(let{project:i,agent:o}of r.projectAgents){let s=await Mr(o,i,t);n.push(s)}for(let i of r.agents){let o=await Mr(i,e,t);n.push(o)}return n}async function dd(r,e){let t=[];for(let n of r){if(!Se[n])continue;let o=await Ko(n,process.cwd(),e);t.push(o)}return t}async function ud(r,e,t){if(t.agent&&t.agent.split(",").map(d=>d.trim()).includes("qoder"))throw new Error("Qoder does not support MCP configuration via DevEco CLI. Use other agents (opencode, trae-cn, cursor, codebuddy).");let n=t.force??!1,i=r.projectAgents.filter(c=>c.agent!=="qoder"),o=r.agents.filter(c=>c!=="qoder"),s={...r,projectAgents:i,agents:o},a=e?await ld(s,e,n):await dd(s.agents,n);a.length>0&&(console.log(Zo("MCP Configuration:")),Xo(a))}async function pd(r){if(r.skill&&r.mcp)throw new Error("Cannot use --skill and --mcp together. Use --skill for skill installation only, or --mcp for MCP configuration only.");let{resolvedPath:e,resolvedProject:t}=vt(r.path,r.project,r.agent);t&&Ee(t,"Project directory",r.force),e&&Ee(e,"Directory",r.force);let n=await Yt(r,e,t);if(r.mcp){await ud(n,t,r);return}let i=Io(),o=await cd(n,i,r);console.log(),o.length>0&&(console.log(Zo("Skill Installation:")),yt(o))}var hd=new sd("init").description("Install the deveco-cli skill or configure the deveco-mcp server into AI agents").option("--agent <agents>","Target agents, comma-separated (e.g. opencode,trae-cn,cursor,qoder,codebuddy); installs to all available agents if omitted").option("--project <path>","Project root directory to install the skill or MCP config into").option("--path <path>","Path to install the skill directly (cannot be used with --project or --agent)").option("--skill","Install the deveco-cli skill only (same as default behavior; explicit for symmetry with --mcp)").option("--mcp","Configure the deveco-mcp server (syntax checking for .ets and C/C++) only; no skill installation").option("-f, --force","Overwrite an existing skill / MCP configuration").action(async r=>{try{await pd(r)}catch(e){console.error(ad(e.message)),process.exit(1)}}),Qo=hd;import{Command as Tu}from"commander";import{McpServer as Cu}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Au}from"@modelcontextprotocol/sdk/server/stdio.js";import*as lt from"path";import{z as Kr}from"zod";var Xt=class{tools=new Map;add(e,t){return this.tools.set(e.name,{definition:e,handler:t}),this}getAll(){return Array.from(this.tools.values())}registerToServer(e){for(let{definition:t,handler:n}of this.getAll())e.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},(async i=>n(i)))}};function Rr(){return new Xt}import*as ge from"fs";import*as ee from"path";import{z as Yr}from"zod";import D from"fs";import*as Zt from"os";import*as S from"path";import md from"json5";var Or="Huawei";var fd=3,rs=3,es="DevEco Studio",is={DevEcoStudio:"deveco_studio"};function Nr(r){if(!D.existsSync(r)||!D.statSync(r).isDirectory())return!1;let e=D.existsSync(S.join(r,"build-profile.json5")),t=D.existsSync(S.join(r,"hvigorfile.js"))||D.existsSync(S.join(r,"hvigorfile.ts"));if(!e||!t)return!1;try{let n=D.readFileSync(S.join(r,"build-profile.json5"),"utf-8");return md.parse(n).app!==void 0}catch{return!1}}function os(r,e,t){if(e>=t)return null;let n=gd(r),i=yd(n);if(i)return i;for(let o of n){let s=os(o,e+1,t);if(s)return s}return null}function gd(r){try{let e=D.readdirSync(r,{withFileTypes:!0}),t=[];for(let n of e)n.isDirectory()&&t.push(S.join(r,n.name));return t}catch{return[]}}function yd(r){for(let e of r)if(Nr(e))return e;return null}function pe(r){if(!r||r.trim()==="")return null;let e=S.resolve(r),t;try{t=D.realpathSync(e)}catch{t=e}if(!D.existsSync(t))return null;if(Nr(t))return t;let n=t;for(let i=1;i<=3;i++){let o=S.dirname(n);if(o===n)break;if(Nr(o))return o;n=o}if(D.statSync(t).isDirectory()){let i=os(t,0,fd);if(i)return i}return null}function ss(r){if(process.platform==="linux")return null;let e=r??Re();if(!e)return null;let t;if(process.platform==="win32")t=S.join(e,"plugins","openharmony");else if(process.platform==="darwin")t=S.join(e,"contents","plugins","openharmony");else return null;let n=S.join(t,"ace-server","out","index.js");return D.existsSync(n)?t:null}var vd=["sdk","default","openharmony","native","llvm","bin","clangd"],Lr=[".idea",".deveco","cxx","compile_commands.json"];function wd(r){return process.platform==="darwin"&&r.endsWith(".app")?S.join(r,"Contents"):r}function ts(r){let e=new Set,t=[r,wd(r)];for(let n of t){let i=S.join(n,...vd);e.add(process.platform==="win32"?i+".exe":i)}return[...e]}function as(r){let e=[],t=process.env.DEVECO_HOME??process.env.DEVECO_PATH;if(t&&t.trim()){for(let i of ts(t.trim()))if(e.push(i),D.existsSync(i))return i}let n=r??Re();if(n){for(let i of ts(n))if(e.push(i),D.existsSync(i))return i}return null}function Qt(r){return S.join(r,...Lr)}function Re(){if(process.platform==="win32"){let r=[S.join("C:\\Program Files",Or,es),S.join("C:\\Program Files (x86)",Or,es)];return ns(r)}if(process.platform==="darwin"){let r=["/Applications/DevEco Studio.app",S.join(process.env.HOME??"","Applications","DevEco Studio.app")];return ns(r)}return null}function ns(r){for(let e of r)if(D.existsSync(e))return e;return null}function se(r){return process.platform==="darwin"?S.join(r,"Contents"):r}function bd(r){if(!r||!D.existsSync(r)||!cs(r))return!1;let e=se(r);return[S.join(e,"plugins","openharmony"),S.join(e,"sdk"),S.join(e,"tools")].some(n=>D.existsSync(n))}function cs(r){try{return D.statSync(r).isDirectory()}catch{return!1}}function Hr(r,e){return!r||!D.existsSync(r)?!1:e===is.DevEcoStudio?bd(r):!1}function en(r,e=is.DevEcoStudio){if(!r)return"";if(Hr(r,e))return r;let t=Sd(r,e);if(t)return t;let n=Pd(r,e);return n||r}function Sd(r,e){let t=r;for(let n=0;n<rs;n++){let i=S.dirname(t);if(!i||i===t)break;if(Hr(i,e))return i;t=i}return null}function Pd(r,e){if(!D.existsSync(r)||!cs(r))return null;let t=[{p:r,depth:0}];for(;t.length>0;){let{p:n,depth:i}=t.shift();if(i>=rs)continue;let o=Ed(n,i,e,t);if(o)return o}return null}function Ed(r,e,t,n){let i;try{i=D.readdirSync(r,{withFileTypes:!0})}catch{return null}for(let o of i){if(!o.isDirectory())continue;let s=S.join(r,o.name);if(Hr(s,t))return s;n.push({p:s,depth:e+1})}return null}function ls(r){return new Promise(e=>setTimeout(e,r))}var Dd=new Set(["c","cc","cpp","cxx","c++","h","hh","hpp","hxx","h++","ipp","ixx","inl","inc","tpp"]);function tn(r){let e=S.extname(r).replace(/^\./,"").toLowerCase();return e.length>0&&Dd.has(e)}function ds(r){return S.extname(r).replace(/^\./,"").toLowerCase()==="c"?"c":"cpp"}function ae(r){let e=r.replace(/\\/g,"/");return process.platform==="win32"&&/^[a-zA-Z]:/.test(e)&&(e=e[0].toUpperCase()+e.slice(1)),e}function jr(r){return ae(r)}function Oe(r){let e=jr(r);return e.startsWith("/")?`file://${e}`:`file:///${e}`}function Et(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Oe(t)}}catch{}return r}function us(r){let e=[],t=r.lastIndexOf("file:/");if(t>=0){let n=r.slice(t).replace(/^file:\/+/,"");if(n){let i=n.startsWith("/")?`file://${n}`:`file:///${n}`,o=Et(i);o!==r&&o!==Et(r)&&e.push(o)}}return e}function nn(){if(process.platform==="win32"){let r=process.env.LOCALAPPDATA??S.join(Zt.homedir(),"AppData","Local");return S.join(r,"devecocli-mcp-server","logs")}return process.platform==="darwin"?S.join(Zt.homedir(),"Library","Logs","devecocli-mcp-server"):S.join(Zt.homedir(),".local","share","devecocli-mcp-server","logs")}function ps(r,e){let t=Id(e),n=Cd(t,r);if(n!==null)return n;let i=Date.now(),s=`${r.replace(/:/g,"\\:")}=${i}`,a=Ad(t,r,s);return kd(e,a),i}function Id(r){let e;try{e=D.readFileSync(r,"utf8")}catch{e=""}return e.length>0?e.split(/\r?\n/):[]}function Cd(r,e){for(let t of r){let n=t.indexOf("=");if(n<=0||t.slice(0,n).replace(/\\:/g,":")!==e)continue;let o=parseInt(t.slice(n+1),10);return Number.isFinite(o)&&o>0?o:null}return null}function Ad(r,e,t){let n=!1,i=r.map(o=>{if(n)return o;let s=o.indexOf("=");return s<=0?o:o.slice(0,s).replace(/\\:/g,":")===e?(n=!0,t):o});return n||i.push(t),i}function kd(r,e){try{D.mkdirSync(S.dirname(r),{recursive:!0})}catch{}try{D.writeFileSync(r,e.join(`
|
|
1229
1229
|
`)+`
|
|
1230
1230
|
`,"utf8")}catch{}}function Fr(r,e,t="[Cleanup]"){try{let n=S.dirname(r);if(!D.existsSync(n))return;let i=Date.now();for(let o of D.readdirSync(n,{withFileTypes:!0}))o.isDirectory()&&Td(S.join(n,o.name),i,e,t)}catch{}}function Td(r,e,t,n){try{let{mtimeMs:i}=D.statSync(r);if(e-i<=t)return;D.rmSync(r,{recursive:!0,force:!0});let o=Math.floor((e-i)/1e3);console.error(`${n} Removed expired dir (age ${Math.floor(o/86400)}d ${Math.floor(o%86400/3600)}h): ${r}`)}catch(i){console.error(`${n} Failed to remove expired dir ${r}: ${i}`)}}function rn(r){let e=r.replace(/sdk\/?$/i,"tools"),t=process.platform==="win32"?"node.exe":"node",n=S.join(e,"node",t);return D.existsSync(n)||process.platform!=="win32"&&(n=S.join(e,"node","bin","node"),D.existsSync(n))?n:process.execPath??"node"}import*as C from"fs";import*as sn from"path";var hs="mcp-server.log",Md="mcp-server",xd={maxSize:10*1024*1024,maxFiles:4},$r=class{fd=null;logDir=null;currentLogFile=null;mode;rotationOptions;currentFileSize=0;currentDate="";isRotating=!1;constructor(e,t){this.rotationOptions={...xd,...t},e?(this.mode="console",this.logDir=null,this.currentLogFile=null):(this.mode="file",this.logDir=nn(),this.currentLogFile=sn.join(this.logDir,hs),C.existsSync(this.logDir)||C.mkdirSync(this.logDir,{recursive:!0}),this.cleanupOrphanLogFiles(),this.openLogFile())}getCurrentDateString(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),i=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${i}`}getRotatedFileName(e,t){return sn.join(this.logDir,`${Md}-${e}.log.${t}`)}fileExists(e){try{return C.accessSync(e,C.constants.F_OK),!0}catch{return!1}}cleanupOrphanLogFiles(){if(this.logDir)try{let e=C.readdirSync(this.logDir),t=[];for(let i of e)if(i===hs||/^mcp-server-\d{4}-\d{2}-\d{2}\.log\.\d+$/.test(i)){let o=sn.join(this.logDir,i),s=C.statSync(o);t.push({name:i,mtime:s.mtime,path:o})}t.sort((i,o)=>o.mtime.getTime()-i.mtime.getTime());let n=1+this.rotationOptions.maxFiles;for(let i=n;i<t.length;i++)try{C.unlinkSync(t[i].path)}catch{}}catch{}}rotateLog(){if(!(this.isRotating||!this.logDir||!this.currentLogFile)){this.isRotating=!0;try{if(this.closeLogFile(),!this.fileExists(this.currentLogFile)){this.isRotating=!1,this.openLogFile();return}let e=this.getCurrentDateString(),t=this.getRotatedFileName(e,this.rotationOptions.maxFiles);this.fileExists(t)&&C.unlinkSync(t);for(let i=this.rotationOptions.maxFiles-1;i>=1;i--){let o=this.getRotatedFileName(e,i),s=this.getRotatedFileName(e,i+1);this.fileExists(o)&&C.renameSync(o,s)}let n=this.getRotatedFileName(e,1);C.renameSync(this.currentLogFile,n),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=C.statSync(this.currentLogFile);this.currentFileSize=e.size}else this.currentFileSize=0}catch{this.currentFileSize=0}try{this.fd=C.openSync(this.currentLogFile,"a")}catch{this.fd=null}}}closeLogFile(){if(this.fd!==null){try{C.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,...n){if(this.mode==="silent")return;let i=n.map(c=>typeof c=="object"?JSON.stringify(c,null,2):String(c)).join(" "),o=i?`${t} ${i}`:t,a=`[${new Date().toLocaleString("sv-SE",{timeZone:"Asia/Shanghai",hour12:!1})+"."+String(new Date().getMilliseconds()).padStart(3,"0")}] [MCP/${e.toUpperCase()}] ${o}
|
|
1231
|
-
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);C.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{C.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},
|
|
1231
|
+
`;if(this.mode==="file"&&this.currentLogFile){if(this.fd===null&&this.openLogFile(),this.fd!==null)try{let c=Buffer.from(a);C.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{C.fsyncSync(this.fd)}catch{}}getLogFilePath(){return this.currentLogFile}getLogDirectory(){return this.logDir}},J=null;function _r(r=!1){J&&J.dispose(),J=new $r(r)}function ms(){J&&(J.dispose(),J=null)}function fs(){J&&J.flush()}function gs(){return J?.getLogFilePath()??null}function ys(){return J?.getLogDirectory()??null}function on(){return J||_r(!1),J}var m={debug:(r,...e)=>on().debug(r,...e),info:(r,...e)=>on().info(r,...e),warn:(r,...e)=>on().warn(r,...e),error:(r,...e)=>on().error(r,...e)};function vs(r){return"method"in r&&!("id"in r)}import{spawn as Od}from"child_process";import{EventEmitter as Nd}from"events";import*as Ze from"fs";import*as Es from"path";import*as ws from"util";var Wr="";function bs(r){if(!r||r==="auto"||r==="stdout"||r==="none"){Wr="";return}Wr=r}function Ss(){return Wr||(ys()??"")}function an(r,...e){if(e.length===0)return r;try{return ws.format(r,...e)}catch{return[r,...e.map(t=>typeof t=="string"?t:JSON.stringify(t))].join(" ")}}var l={info(r,...e){m.info(`[lsp] ${an(r,...e)}`)},warn(r,...e){m.warn(`[lsp] ${an(r,...e)}`)},error(r,...e){m.error(`[lsp] ${an(r,...e)}`)},debug(r,...e){m.debug(`[lsp] ${an(r,...e)}`)}};import*as Dt from"fs";import*as Ur from"os";import*as Xe from"path";import Rd from"json5";function Y(r){if(!Dt.existsSync(r))return null;try{let e=Dt.readFileSync(r,"utf-8");return e.trim()?Rd.parse(e):null}catch{return null}}function he(r){try{let e=Xe.resolve(r),t=new URL(`file://${e}`).toString();if(Ur.platform()==="win32"){let n=t.match(/^file:\/\/\/([A-Za-z]):/);if(n){let i=n[1].toUpperCase(),o=t.substring(`file:///${n[1]}:`.length);t=`file:///${i}%3A${o}`}}return t}catch{return r}}function cn(r){return r&&r.replace(/\\/g,"/")}function F(r){let e=Xe.normalize(r).replace(/\\/g,"/");if(Ur.platform()==="win32"){let t=e.match(/^([A-Za-z]):/);t&&(e=`${t[1].toUpperCase()}:${e.substring(2)}`)}return e}function Ps(r){return Xe.join(r,"build-profile.json5")}var ln=class extends Nd{constructor(t){super();this.config=t}config;process=null;buffer=Buffer.alloc(0);isClosing=!1;async start(){let t=Es.join(this.config.logPath,"lspLog");Ze.existsSync(t)||Ze.mkdirSync(t,{recursive:!0}),Ze.existsSync(this.config.indexingDataLocation)||Ze.mkdirSync(this.config.indexingDataLocation,{recursive:!0});let n=this.config.nodeMaxOldSpaceSize??8192,i=F(t),o=["--expose-gc",`--max-old-space-size=${n}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${i}`,this.config.serverPath,"--stdio",`--logger-path=${i}`,"--logger-level=TRACE"];l.info(`[LspClient] Starting process: node ${o.join(" ")}`);let s=process.execPath??"node";l.info(`[LspClient] nodePath: ${s}`),this.process=Od(s,o,{cwd:this.config.cwd||process.cwd(),stdio:["pipe","pipe","pipe"],windowsHide:!0}),this.process.stdout?.on("data",a=>{this.handleData(a)}),this.process.stderr?.on("data",a=>{let c=a.toString("utf8").trim();l.error(`[LspClient] stderr: ${c}`),this.isClosing||this.emit("error",new Error(`[LspClient] stderr: ${c}`))}),this.process.on("exit",a=>{l.info(`[LSP EXIT] code=${a}`),this.isClosing||this.emit("error",new Error(`LSP process exited with code ${a}`))}),await new Promise(a=>setTimeout(a,500)),l.info("[LspClient] start lsp process success")}sendRaw(t,n){if(!this.process?.stdin?.writable){l.warn("[LspClient] Cannot send message, stdin not writable");return}l.info(`[LspClient] send message: ${n}`);let i=this.buildLspMessage(t);this.process.stdin.write(i,"utf8")}send(t,n,i){let o={jsonrpc:"2.0",method:t,params:n};i!==void 0&&(o.id=i),this.sendRaw(JSON.stringify(o),t)}buildLspMessage(t){return`Content-Length: ${Buffer.from(t,"utf8").length}\r
|
|
1232
1232
|
\r
|
|
1233
1233
|
${t}`}handleData(t){for(this.buffer=Buffer.concat([this.buffer,t]);;){let n=this.buffer.indexOf(`\r
|
|
1234
1234
|
\r
|
|
1235
|
-
`);if(n===-1)break;let o=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){l.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(o[1],10),a=n+4,c=a+s;if(this.buffer.length<c)break;let d=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(d);if(u&&u.rest.length>0){l.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${d.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",d),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),n.off("exit",a),i())},a=()=>s();n.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let n=t.search(/\S/);if(n<0||t[n]!=="{"&&t[n]!=="[")return null;let i=0,o=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let d=t.slice(n,a+1),u=t.slice(a+1);return{json:d,rest:u}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var dn=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,n){l.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);i&&(i(t,n),this.callbacks.delete(e))}registerTimeout(e,t,n,i){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let o=setTimeout(()=>{l.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},n);this.timeouts.set(e,o)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)}clear(e){this.clearTimeout(e),this.callbacks.delete(e)}};var un=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 n=`${e}:${t}`;if(this.uniqueMessages.has(n)){l.info(`[Diagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new Br(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)}},Br=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var pn=class{map=new Map;register(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}unregister(e,t){let n=this.map.get(e);n&&(t!==void 0?n.delete(t):n.clear(),n.size===0&&this.map.delete(e))}invoke(e,...t){let n=this.map.get(e);if(n)for(let i of n)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function m(r){return typeof r=="object"&&r!==null}function zr(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}var Ld={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"},hn={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},g={...Ld,...hn},M="2.0",J={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"};function Hd(r){if(!m(r))return!1;let e=r.textDocument;return m(e)&&typeof e.uri=="string"}function jd(r){return m(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}var fn=class r{client;isInitialized=!1;stopOnce=null;callbacks=new pn;requestCallbacks=new dn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new ln(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(){await this.client.start()}stop(){return this.stopOnce||(this.stopOnce=(async()=>{l.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.EXIT,params:{}}),J.EXIT),l.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(g.BROADCAST),this.callbacks.register(g.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(g.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(g.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(g.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:M,method:g.INITIALIZED,params:{editors:e}}),J.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:M,id:0,result:{}}),J.EMPTY)}sendAsyncRequest(e,t,n,i){if(!m(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Hd(t)){l.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){l.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let o=t.textDocument.uri,s=he(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;l.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(l.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!jd(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),g.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!m(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){l.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;l.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),J.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=he(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new un(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,hn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),J.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=he(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,hn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),J.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=he(e);l.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){l.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.DID_CLOSE,params:{textDocument:{uri:n}}}),J.DID_CLOSE)}getDiagnosticMessage(e){let t=he(e),n=this.diagnosticMap.get(t);return n?n.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let n=t instanceof Error?t.message:String(t);l.error(`[LSP] JSON parse error: ${n}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let n=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,g.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:M,method:g.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e){switch(e){case g.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(g.MODULE_INIT_FINISH),this.callbacks.unregister(g.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case g.INDEXING_PROGRESS_UPDATE:return l.info("[LSP] handleLspMessage, receive onIndexingProgressUpdate"),this.callbacks.invoke(g.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case g.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case g.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case g.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case g.ON_ASYNC_HOVER:this.handleAsyncResponse(t,g.HOVER);return;case g.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,g.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case g.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,g.REFERENCES);return;default:l.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){l.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;m(t)&&m(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){l.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:M,method:g.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){l.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){l.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}l.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){l.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!m(n)){l.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=n.requestId;if(typeof i!="number"){l.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,n)}handleForceOpenFile(e){if(!e){l.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,g.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){l.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let i=this.diagnosticMap.get(t);if(!i){l.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(n,JSON.stringify(s))}):i.setReceivedType(n),i.hasReceivedAllTypes(r.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,g.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),n={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=n[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let n=e[t];n&&typeof n.line=="number"&&(n.line=n.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,r.DIAGNOSTIC_TIMEOUT_MS,()=>{let n=this.diagnosticMap.get(e),i=n?n.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,i){let o={uri:e,diagnostics:n,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Ln from"path";import*as Sn from"path";var mn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var gn=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var yn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var vn=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var wn=class{typeSetting=new yn;parameterNames=new vn};var bn=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=F(Sn.dirname(t)),this.indexingDataLocation=F(i),this.loggerPath=F(Sn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new mn;gutterIconsSetting=new gn;inlayHintsSetting=new wn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Ds from"path";var It=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(F(Ds.join(e,"src","main","resources")))}};var Fd="OS",Qe=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${Fd}`;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 It(e)):this.buildProfileParam=new It}toString(){return JSON.stringify(this)}};var et=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as W from"path";import*as rt from"fs";var Pn=class{modulePath;dependencies={};dynamicDependencies={}};var Ne=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var tt=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as fe from"path";import*as En from"fs";var nt=class{name="";version="";storePath="";dependencyPath="";path=""};var I={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:"oh-package.json5"},Ct=`${I.HVIGOR_CACHE}/${I.DEPENDENCY}`,Le=`${I.DEPENDENCY}${I.JSON5}`;var At=class r{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,n){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,n){this.dependencyPath=e,this.modulePath=t,this.projectPath=n,this.fileSpecPattern=r.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=fe.join(this.dependencyPath,I.OH_PACKAGE_JSON5),n=Y(t);n&&(this.dependencies=this.getDependencyList(n,I.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,I.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,I.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!m(e))return n;let i=e[t];if(!m(i))return n;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){l.error(`${o} package dependency value is not String ${t}`);continue}let a=new nt;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,i){if(!(!e||!t))try{let o=fe.normalize(fe.join(this.modulePath,I.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=o;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=o;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),fe.isAbsolute(s)){n.dependencyPath=o;return}i||(o=fe.normalize(fe.join(this.modulePath,s))),En.existsSync(o)&&En.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as kt from"fs";import*as De from"path";import $d from"json5";var Dn=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;constructor(e=""){this.projectPath=e}parseDependencies(e){let t=this.getLockFilePath(),n=this.readLockFile(t);if(!n)return!1;let i=this.validateLockFile(n);return i.valid?(this.extractDependencies(i.modules,i.packages,e),!0):!1}getLockFilePath(){return De.join(this.projectPath,I.OH_MODULES_PATH,I.OHPM_PATH,I.LOCK_JSON5_FILE)}readLockFile(e){if(!kt.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=kt.readFileSync(e,"utf8"),n=$d.parse(t);return n||(l.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return l.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!m(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=this.parseStorePathMap(t),this.finalDependencies=this.getDependencyList(e,I.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,I.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,I.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!m(e))return t;for(let[n,i]of Object.entries(e)){if(!m(i)){l.error(`${n} value is not json object`);continue}typeof i.storePath=="string"&&t.set(n,i.storePath)}return t}getDependencyList(e,t,n){if(!m(e))return[];for(let[i,o]of Object.entries(e))if(m(o)){let s=typeof o.name=="string"?o.name:"";if(n==="."&&s===""||s===n)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,n){let i=e[n];if(!m(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!m(s))return[];for(let[a,c]of Object.entries(s)){if(!m(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",b=new nt;b.name=a,b.version=u.startsWith(r.FILE_DEPENDENCY_PREFIX)?u.substring(r.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(b,n,a,d,u);let k=`${a}@${u}`;this.storePathMap.has(k)&&(b.storePath=this.storePathMap.get(k)||""),o.push(b)}return o}parseDependencyPath(e,t,n,i,o){let s=De.normalize(De.join(this.projectPath,t,I.OH_MODULES_PATH,n));try{let a=o;o.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(a=o.substring(r.FILE_DEPENDENCY_PREFIX.length));let c=a;if(De.isAbsolute(c)||(c=De.join(this.projectPath,a)),!kt.existsSync(c)){e.dependencyPath=s;return}if(e.path=i,this.fileNameForOhpm.test(o)){e.dependencyPath=s;return}e.dependencyPath=c}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var He=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Ps(this.projectRoot);try{let t=Y(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Is(r){return m(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Tt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new He(this.projectPath)}projectPath;sdkPath;moduleInfoParse;getAllDependencyMap(e){let t=this.projectPath,n=W.join(t,Ct),i=W.join(n,Le);if(!rt.existsSync(n)||!rt.existsSync(i)){let a="Dependency map or JSON not found";return l.warn(`[Parser] getAllDependencyMap failed: ${a}.`),{status:"ERROR",message:`${a}, please rebuild project`}}let o=new tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let a="No modules found in build-profile.json5";return l.warn(`[Parser] getAllDependencyMap failed: ${a}.`),{status:"ERROR",message:a}}for(let a of s)Is(a)&&this.parseSingleModule(a,n,o,e);return{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=W.join(n,Ct),o=W.join(i,Le);if(!rt.existsSync(i)||!rt.existsSync(o))return l.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(d=>d.trim()).filter(Boolean)):null,a=new tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return l.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let d of c){if(!Is(d))continue;let u=d.name;if(s&&!s.has(u))continue;let b=d.srcPath,k=W.resolve(this.projectPath,b),ce=W.join(i,u),je=F(k),Fe=this.buildModuleDependencies(u,je,ce,a);Fe.moduleName=u,t.push(Fe)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=W.resolve(this.projectPath,s),c=W.join(t,o),d=F(a),u=new Qe(d),b=this.buildModuleDependencies(o,d,c,n);this.parseModuleJson5(d,u);let k=this.parseMainPages(d);this.parseSdkJson(u),this.parseCompatibleSdkVersion(u),u.moduleName=o,u.moduleType=o,u.packageName=o,u.moduleDependencies=b,u.moduleJsonParam=new et(k),i.push(u)}buildModuleDependencies(e,t,n,i){let o=new tt(this.projectPath,e,t);At.getInstance(n,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Pn;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let n={},i={};for(let o of e.finalDependencies)n[o.name]=new Ne(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Ne(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=W.join(e,I.OH_PACKAGE_JSON5);if(!rt.existsSync(n))return;At.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=new Dn(e.projectPath);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)}parseModuleJson5(e,t){let n=W.join(e,"src","main","module.json5"),i=Y(n);if(!m(i)||!m(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(m(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)m(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=W.join(e,"src","main","resources","base","profile","main_pages.json"),n=Y(t);return!m(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=W.join(this.sdkPath,"default","sdk-pkg.json"),n=Y(t);!m(n)||!m(n.data)||(typeof n.data.apiVersion=="string"&&(e.compileSdkLevel=n.data.apiVersion),typeof n.data.releaseType=="string"&&(e.compileSdkType=n.data.releaseType),typeof n.data.version=="string"&&(e.compileSdkVersion=n.data.version))}parseCompatibleSdkVersion(e){let t=W.join(this.projectPath,"build-profile.json5"),n=Y(t);if(!m(n)||!m(n.app)||!Array.isArray(n.app.products)||n.app.products.length===0)return;let i=n.app.products[0];if(!m(i)||typeof i.compatibleSdkVersion!="string")return;let[o,s]=this.parseBySplit(i.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=s}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!m(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 In=class{constructor(e=[]){this.valueSet=e}valueSet};var it=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Cs=(y=>(y[y.File=1]="File",y[y.Module=2]="Module",y[y.Namespace=3]="Namespace",y[y.Package=4]="Package",y[y.Class=5]="Class",y[y.Method=6]="Method",y[y.Property=7]="Property",y[y.Field=8]="Field",y[y.Constructor=9]="Constructor",y[y.Enum=10]="Enum",y[y.Interface=11]="Interface",y[y.Function=12]="Function",y[y.Variable=13]="Variable",y[y.Constant=14]="Constant",y[y.String=15]="String",y[y.Number=16]="Number",y[y.Boolean=17]="Boolean",y[y.Array=18]="Array",y[y.Object=19]="Object",y[y.Key=20]="Key",y[y.Null=21]="Null",y[y.EnumMember=22]="EnumMember",y[y.Struct=23]="Struct",y[y.Event=24]="Event",y[y.Operator=25]="Operator",y[y.TypeParameter=26]="TypeParameter",y))(Cs||{}),As=()=>Object.values(Cs).filter(r=>typeof r=="number");var Cn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var An=class{applyEdit=!0;workspaceEdit=new Cn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new In(As());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new it;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var kn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Tn=class{constructor(e=[]){this.valueSet=e}valueSet};var Mn=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ks=(v=>(v[v.Text=1]="Text",v[v.Method=2]="Method",v[v.Function=3]="Function",v[v.Constructor=4]="Constructor",v[v.Field=5]="Field",v[v.Variable=6]="Variable",v[v.Class=7]="Class",v[v.Interface=8]="Interface",v[v.Module=9]="Module",v[v.Property=10]="Property",v[v.Unit=11]="Unit",v[v.Value=12]="Value",v[v.Enum=13]="Enum",v[v.Keyword=14]="Keyword",v[v.Snippet=15]="Snippet",v[v.Color=16]="Color",v[v.File=17]="File",v[v.Reference=18]="Reference",v[v.Folder=19]="Folder",v[v.EnumMember=20]="EnumMember",v[v.Constant=21]="Constant",v[v.Struct=22]="Struct",v[v.Event=23]="Event",v[v.Operator=24]="Operator",v[v.TypeParameter=25]="TypeParameter",v))(ks||{}),Ts=()=>Object.values(ks).filter(r=>typeof r=="number");var xn=class{completionItemKind=new Tn(Ts());completionItem=new Mn;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Rn=class{synchronization=new kn;completion=new xn;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 it;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var On=class{workspace=new An;textDocument=new Rn;notebookDocument=null;window=null;general=null;experimental=null};var Nn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function ot(r){return m(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function Ms(r){return m(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function xs(r){if(!m(r)||typeof r.text!="string")return!1;let e=r.range;return m(e)?ot(e.start)&&ot(e.end):!1}var Hn=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=Ln.resolve(t,"ace-server","out","index.js"),this.logPath=Ss(),this.indexLogPath=i||this.logPath,this.messageHandle=new fn({serverPath:this.serverPath,logPath:this.logPath,nodeMaxOldSpaceSize:this.nodeMaxOldSpaceSize,indexingDataLocation:this.indexLogPath}),this.messageHandle.setBroadcastToClients(s=>this.onLspMessage(s))}sdkPath;rootUri;nodeMaxOldSpaceSize;messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}initTimeoutMs=60*1e3;async start(e,t){let n=!1;try{l.info(`serverPath: ${this.serverPath}`),l.info(`rootUri: ${this.rootUri}`),l.info(`sdkPath: ${this.sdkPath}`),l.info(`logPath: ${this.logPath}`),await this.messageHandle.start();let i=he(this.rootUri),o=new bn(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Tt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s,this.currentParams=new Nn(i,o,new On),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:M,method:g.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((d,u)=>{this.messageHandle.onIndexingProgressUpdate(u),this.messageHandle.onInitializationCompleted(d)},"LSP initialization",this.initTimeoutMs),this.messageHandle.sendInitialized(e),n=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),l.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(n)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=he(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=m(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:M,method:n,params:{uri:typeof o.uri=="string"?o.uri:t,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(a=>typeof a=="string"):[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(n,i)=>{l.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${n}`);let o={jsonrpc:M,id:e,result:m(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Tt(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){l.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let d=n.getDependenciesOnly();this.markDependencyTypesIncremental(d);let u=this.mergeDepsOnlyIntoModuleList(d,i);return this.applyModuleModelsUpdate(u),l.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=d,d}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return l.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];l.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=n.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),l.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,n),c=i.dependencies??{},d=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,b)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,b)}),this.markAddAndDeleteInDeps(a,d,(u,b)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,b)})}}getOldDepsForModule(e,t,n){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||n(i,e[i])}makeDeleteEntry(e,t){return new Ne({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Qe(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new et([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let i=new Map(n.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=cn(Ln.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=cn(Ln.join(t,"default/openharmony/ets/api")),o=cn(Ln.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case g.HOVER:this.handleHoverRequest(e);break;case g.DEFINITION:this.handleDefinitionRequest(e);break;case g.REFERENCES:this.handleReferencesRequest(e);break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!m(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof o!="number"){l.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_HOVER,t,o,J.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!m(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_DEFINITION,t,o,J.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!m(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/references, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_FIND_USAGES,t,o,J.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!vs(e)){l.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case g.DID_OPEN:this.handleDidOpenNotification(e);break;case g.DID_CHANGE:this.handleDidChangeNotification(e);break;case g.DID_CLOSE:this.handleDidCloseNotification(e);break;case g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case g.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!Ms(n)||!zr(i)){l.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:i,textDocument:n};this.registerDiagnosticCallback(n.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!m(n)||typeof n.uri!="string"||typeof n.version!="number"){l.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(i)||!i.every(xs)){l.error("Invalid client textDocument/didChange, contentChanges invalid");return}let o=n.uri,s=n.version;this.registerDiagnosticCallback(o),this.messageHandle.onAsyncDidChange({uri:o,version:s,contentChanges:i})}handleDidCloseNotification(e){let t=e.params;if(!m(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!m(n)||typeof n.uri!="string"){l.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let i=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(n.uri,i)}handleDidChangePackageDependencies(e){let t=e.params;if(!m(t)){l.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:n}=t;if(!Array.isArray(n)||n.length===0){l.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!m(t)){l.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:n}=t;if(!Array.isArray(n)){l.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(n)}withResettableTimeout(e,t,n){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}async dispose(){await this.messageHandle.stop()}};import*as me from"fs";import*as V from"path";import{createHash as _d}from"crypto";import{EventEmitter as Wd}from"events";var jn=class extends Wd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}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()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||(this.watchFile(i),l.info(`[ConfigFileWatcher] Started watching: ${i}`));for(let i of n)t.has(i)||(this.unwatchFile(i),l.info(`[ConfigFileWatcher] Stopped watching: ${i}`));l.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!me.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=me.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{l.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),l.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:n,moduleName:i.name})}}emitModuleRemovedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:n,removedModuleName:i.name})}}emitModuleRenamedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=V.join(this.projectRoot,I.OH_PACKAGE_JSON5);me.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=V.resolve(this.projectRoot,o.srcPath),a=V.join(s,I.OH_PACKAGE_JSON5);me.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return V.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=me.readFileSync(t,"utf-8");return _d("sha256").update(n).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let n=this.computeFileHash(t);n&&this.contentHashes.set(t,n);let i=me.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{l.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch ${t}: ${n instanceof Error?n.message:String(n)}`)}}unwatchFile(t){let n=this.watchers.get(t);n&&(n.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){l.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){l.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),l.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:V.basename(t),relativePath:V.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),l.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ie from"fs";import*as Q from"path";import{createHash as Ud}from"crypto";import{EventEmitter as Bd}from"events";var Fn=class extends Bd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=Q.join(t,Ct)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ie.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ie.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{l.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){l.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),l.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return F(Q.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===I.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Le)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Q.join(this.depMapDir,n);Ie.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,l.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Q.join(this.depMapDir,I.OH_PACKAGE_JSON5),n=Q.join(this.depMapDir,Le),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:Q.join(this.depMapDir,s.name,I.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ie.existsSync(s))continue;let c=this.canonicalPath(s),d=this.computeFileHash(s);if(!d)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,d);continue}u!==d&&(this.contentHashes.set(c,d),l.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Q.join(this.depMapDir,Le);try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}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,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){l.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(l.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){l.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let d of o)s.delete(d);if(o.size===0&&s.size===0&&a.length===0){l.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return F(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:n,bySrcPath:i}}detectModuleRenames(t,n,i,o){for(let[s,a]of t){let c=n.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let d=Q.join(this.depMapDir,a.name,I.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(d)),l.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),l.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,i){for(let[o]of t)i.has(o)||n.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,n,i){for(let[o]of t)if(!i.has(o)&&!n.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=Q.join(this.depMapDir,o,I.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),n=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);l.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(n,o,a,c),this.detectAddedModules(o,n,c),this.detectRemovedModules(n,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Ie.readFileSync(t,"utf-8");return Ud("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as zd}from"child_process";import*as _n from"path";import*as $n from"fs";var Vd=600*1e3;function qd(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function Yd(r){let e="",t="";return r.stdout?.on("data",n=>{e+=n.toString()}),r.stderr?.on("data",n=>{t+=n.toString()}),{stdout:e,stderr:t}}function Gd(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1235
|
+
`);if(n===-1)break;let o=this.buffer.slice(0,n).toString("ascii").match(/Content-Length:\s*(\d+)/i);if(!o){l.warn("[LspClient] Invalid LSP header, drop until next packet"),this.buffer=this.buffer.slice(n+4);continue}let s=parseInt(o[1],10),a=n+4,c=a+s;if(this.buffer.length<c)break;let d=this.buffer.slice(a,c).toString("utf8"),u=this.recoverFramedJson(d);if(u&&u.rest.length>0){l.warn(`[LspClient] recovered mixed LSP frame, bodyLen=${d.length}, restLen=${u.rest.length}`),this.emit("message",u.json),this.buffer=Buffer.concat([Buffer.from(u.rest,"utf8"),this.buffer.slice(c)]);continue}this.emit("message",d),this.buffer=this.buffer.slice(c)}}waitForExitOrTimeout(t){let n=this.process;return!n||n.exitCode!==null||n.signalCode!==null?Promise.resolve():new Promise(i=>{let o=!1,s=()=>{o||(o=!0,clearTimeout(c),n.off("exit",a),i())},a=()=>s();n.once("exit",a);let c=setTimeout(s,t)})}recoverFramedJson(t){let n=t.search(/\S/);if(n<0||t[n]!=="{"&&t[n]!=="[")return null;let i=0,o=!1,s=!1;for(let a=n;a<t.length;a++){let c=t[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c==='"'&&(o=!1);continue}if(c==='"'){o=!0;continue}if(c==="{"||c==="["){i++;continue}if((c==="}"||c==="]")&&(i--,i===0)){let d=t.slice(n,a+1),u=t.slice(a+1);return{json:d,rest:u}}}return null}stop(){this.isClosing=!0;let t=this.process;if(!t)return;if(this.process=null,t.exitCode===null&&t.signalCode===null)try{t.kill()}catch{}}};var dn=class{callbacks=new Map;timeouts=new Map;register(e,t){this.callbacks.set(e,t)}emit(e,t,n){l.info(`[RequestCallbackManager] emit, method: ${t}, key: ${e}`),this.clearTimeout(e);let i=this.callbacks.get(e);i&&(i(t,n),this.callbacks.delete(e))}registerTimeout(e,t,n,i){this.timeouts.has(e)&&clearTimeout(this.timeouts.get(e));let o=setTimeout(()=>{l.info(`[RequestCallbackManager] timeout, key=${e}, method=${t}`),i(),this.timeouts.delete(e)},n);this.timeouts.set(e,o)}clearTimeout(e){let t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e))}deleteCallback(e){this.callbacks.delete(e)}hasCallback(e){return this.callbacks.has(e)}clear(e){this.clearTimeout(e),this.callbacks.delete(e)}};var un=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 n=`${e}:${t}`;if(this.uniqueMessages.has(n)){l.info(`[Diagnostic] addMessage: duplicate message=${n}`);return}this.uniqueMessages.add(n),this.messages.push(new Br(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)}},Br=class{version=-1;diagnostics;constructor(e,t){this.version=e,this.diagnostics=t}};var pn=class{map=new Map;register(e,t){let n=this.map.get(e);n||(n=new Set,this.map.set(e,n)),n.add(t)}unregister(e,t){let n=this.map.get(e);n&&(t!==void 0?n.delete(t):n.clear(),n.size===0&&this.map.delete(e))}invoke(e,...t){let n=this.map.get(e);if(n)for(let i of n)try{i(...t)}catch(o){console.error(`[CallbackRegistry] invoke("${String(e)}") callback error:`,o)}}invokeOnce(e,...t){this.invoke(e,...t),this.unregister(e)}clear(){this.map.clear()}has(e){let t=this.map.get(e);return t!==void 0&&t.size>0}};function f(r){return typeof r=="object"&&r!==null}function zr(r){return Array.isArray(r)&&r.every(e=>typeof e=="string")}var Ld={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"},hn={MODULE_INIT_FINISH:"aceProject/onModuleInitFinish",INDEXING_PROGRESS_UPDATE:"aceProject/onIndexingProgressUpdate",BROADCAST:"lsp/broadcast",ARKTS_ERROR:"arkts/error",ON_FORCE_OPEN_FILE:"aceProject/onForceOpenFile",ON_PACKAGE_CHANGE_FINISH:"aceProject/onPackageChangeFinish",PUBLISH_DIAGNOSTICS:"textDocument/publishDiagnostics",HOVER:"textDocument/hover",TEXT_DOCUMENT_ON_ASYNC_DEFINITION:"textDocument/onAsyncDefinition",REFERENCES:"textDocument/references",DID_OPEN:"textDocument/didOpen",DID_CHANGE:"textDocument/didChange",DEFINITION:"textDocument/definition",ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:"textDocument/onDidChangePackageDependencies",WORKSPACE_DID_CHANGE_CONFIGURATION:"workspace/didChangeConfiguration",ARKTS_INITIALIZED:"arkts/initialized",ARKTS_INITIALIZATION_FAILED:"arkts/initializationFailed",ARKTS_INDEXING_PROGRESS:"arkts/indexingProgress",ARKTS_SYNC_PROJECT:"arkts/syncProject",ARKTS_SYNC_COMPLETED:"arkts/syncCompleted",ARKTS_REINITIALIZING:"arkts/reinitializing",WORKSPACE_DID_CHANGE_WATCHED_FILES:"workspace/didChangeWatchedFiles"},g={...Ld,...hn},M="2.0",K={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"};function Hd(r){if(!f(r))return!1;let e=r.textDocument;return f(e)&&typeof e.uri=="string"}function jd(r){return f(r)?typeof r.uri=="string"&&typeof r.type=="number":!1}var mn=class r{client;isInitialized=!1;stopOnce=null;callbacks=new pn;requestCallbacks=new dn;diagnosticMap=new Map;static DIAGNOSTIC_TIMEOUT_MS=20*1e3;static EXPECTED_DIAGNOSTIC_TYPES=new Set([1e3,2e3,3e3,3001]);constructor(e){this.client=new ln(e),this.client.on("message",t=>this.handleRawMessage(t)),this.client.on("error",t=>this.handleError(t))}async start(){await this.client.start()}stop(){return this.stopOnce||(this.stopOnce=(async()=>{l.info("[ClientMessageHandle] Sending exit notification to LSP"),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.EXIT,params:{}}),K.EXIT),l.info("[ClientMessageHandle] Waiting for LSP process to exit"),await this.client.waitForExitOrTimeout(300),l.info("[ClientMessageHandle] LSP exit wait completed, calling stop"),this.client.stop()})()),this.stopOnce}setBroadcastToClients(e){this.callbacks.unregister(g.BROADCAST),this.callbacks.register(g.BROADCAST,e)}broadcastToClients(e){this.callbacks.invoke(g.BROADCAST,e)}onInitializationCompleted(e){this.isInitialized?e():this.callbacks.register(g.MODULE_INIT_FINISH,e)}onIndexingProgressUpdate(e){this.callbacks.register(g.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:M,method:g.INITIALIZED,params:{editors:e}}),K.INITIALIZED),this.client.sendRaw(JSON.stringify({jsonrpc:M,id:0,result:{}}),K.EMPTY)}sendAsyncRequest(e,t,n,i){if(!f(t)){l.warn(`[LSP] sendAsyncRequest invalid params, method=${e}`);return}if(!Hd(t)){l.warn(`[LSP] sendAsyncRequest missing textDocument.uri, method=${e}, params=${JSON.stringify(t)}`);return}if(typeof n!="number"){l.warn(`[LSP] sendAsyncRequest invalid requestId, method=${e}, requestId=${String(n)}`);return}let o=t.textDocument.uri,s=he(o);t.textDocument.uri=s,delete t.requestId;let a=i??e;l.info(`[LSP] sendAsyncRequest ${a}, filePath: ${o}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:e,params:{params:t,requestId:n}}),a)}onDidChangeWatchedFiles(e){if(l.info(`[LSP] onDidChangeWatchedFiles, params=${JSON.stringify(e)}`),e.length===0)return;let t=[];for(let n of e){if(!jd(n)){l.warn(`[LSP] onDidChangeWatchedFiles, param is missing 'uri' or 'type': ${JSON.stringify(n)}`);continue}t.push(n)}this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.WORKSPACE_DID_CHANGE_WATCHED_FILES,params:{changes:t}}),g.WORKSPACE_DID_CHANGE_WATCHED_FILES)}sendModuleDependencyUpdate(e){if(!f(e)||!Array.isArray(e.moduleSet)||e.moduleSet.length===0){l.warn("[LSP] sendModuleDependencyUpdate, moduleSet is empty or null");return}let t=e.moduleSet;l.info(`[LSP] sending module dependency updated, count: ${t.length}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES,params:{params:e}}),K.ON_DID_CHANGE_PACKAGE_DEPENDENCIES)}onAsyncOpenFile(e){let t=e.textDocument.uri,n=t.split(".").pop()||"";if(n!=="ets"&&n!=="ts")return;let i=he(t);e.textDocument.uri=i,l.info(`[LSP] onAsyncOpenFile, uri: ${i}`);let o=this.diagnosticMap.get(i);o||(o=new un(i),this.diagnosticMap.set(i,o),this.registerDiagnosticTimeout(i,hn.PUBLISH_DIAGNOSTICS)),e.isFromEditor&&(o.isFromEditor=!0),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_ASYNC_DID_OPEN,params:{params:{editorFiles:e.editorFiles,textDocument:e.textDocument}}}),K.ON_ASYNC_DID_OPEN)}onAsyncDidChange(e){let t=he(e.uri),n=this.diagnosticMap.get(t);n&&(n.clear(),this.registerDiagnosticTimeout(t,hn.PUBLISH_DIAGNOSTICS)),l.info(`[LSP] onAsyncDidChange, uri: ${t}`),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.ON_ASYNC_DID_CHANGE,params:{editorFiles:[e.uri],params:{textDocument:{uri:t,version:e.version===0?null:e.version},contentChanges:e.contentChanges}}}),K.ON_ASYNC_DID_CHANGE)}closeFile(e,t){let n=he(e);l.info(`[LSP] didClose, uri: ${n}`);let i=this.diagnosticMap.get(n);if(!t&&(!i||i.isFromEditor)){l.info(`[LSP] closeFile skip, !diagnostic: ${!i}, isFromEditor: ${i?.isFromEditor}`);return}this.cleanupDiagnosticState(n),this.client.sendRaw(JSON.stringify({jsonrpc:M,method:g.DID_CLOSE,params:{textDocument:{uri:n}}}),K.DID_CLOSE)}getDiagnosticMessage(e){let t=he(e),n=this.diagnosticMap.get(t);return n?n.getMessages():[]}clear(e){this.diagnosticMap.get(e)?.clear()}handleRawMessage(e){try{let t=JSON.parse(e);this.handleLspMessage(t)}catch(t){let n=t instanceof Error?t.message:String(t);l.error(`[LSP] JSON parse error: ${n}, raw: ${e}`)}}handleError(e){let t=this.getPendingDiagnosticUris();if(t.length>0){let n=JSON.stringify({message:e.message,severity:"Error",severityStr:"Error"});for(let i of t)this.finalizeDiagnostic(i,g.PUBLISH_DIAGNOSTICS,[n]);return}this.broadcastToClients({jsonrpc:M,method:g.ARKTS_ERROR,params:{message:e.message}})}handleLspMessage(e){let t=e.method;t!==void 0&&(!this.isInitialized&&this.handlePreInitMessage(t)||this.handlePostInitMessage(t,e))}handlePreInitMessage(e){switch(e){case g.MODULE_INIT_FINISH:return l.info("[LSP] handleLspMessage, receive onModuleInitFinish"),this.isInitialized=!0,this.callbacks.invokeOnce(g.MODULE_INIT_FINISH),this.callbacks.unregister(g.INDEXING_PROGRESS_UPDATE),this.client.emit("initialized_done"),!0;case g.INDEXING_PROGRESS_UPDATE:return l.info("[LSP] handleLspMessage, receive onIndexingProgressUpdate"),this.callbacks.invoke(g.INDEXING_PROGRESS_UPDATE),!0;default:return!1}}handlePostInitMessage(e,t){switch(e){case g.ON_FORCE_OPEN_FILE:this.handleOnForceOpenFile(t);return;case g.ON_PACKAGE_CHANGE_FINISH:l.info("[LSP] handleLspMessage, receive onPackageChangeFinish"),this.handlePackageChangeFinish(t);return;case g.PUBLISH_DIAGNOSTICS:this.handlePublishDiagnostics(t);return;case g.ON_ASYNC_HOVER:this.handleAsyncResponse(t,g.HOVER);return;case g.ON_ASYNC_DEFINITION:this.handleAsyncResponse(t,g.TEXT_DOCUMENT_ON_ASYNC_DEFINITION);return;case g.ON_ASYNC_FIND_USAGES:this.handleAsyncResponse(t,g.REFERENCES);return;default:l.warn(`[LSP] handleLspMessage: no handler for notification, ignoring, method: ${e}, initialized: ${this.isInitialized}`)}}handleOnForceOpenFile(e){l.info("[LSP] handleLspMessage, receive onForceOpenFile");let t=e.params;f(t)&&f(t.result)&&typeof t.result.uri=="string"&&this.handleForceOpenFile(t.result.uri)}handlePublishDiagnostics(e){l.info("[LSP] handleLspMessage, receive publishDiagnostics");let t=e.params;t&&this.parseDiagnostics(t)}handlePackageChangeFinish(e){let t=e.params,n={jsonrpc:M,method:g.ON_PACKAGE_CHANGE_FINISH,params:[!1]};if(!t||!Array.isArray(t)){l.warn("[LSP] aceProject/onPackageChangeFinish params invalid"),this.broadcastToClients(n);return}if(!(t.length>0&&t[0]===!0)){l.warn("[LSP] aceProject/onPackageChangeFinish: package request failed"),this.broadcastToClients(n);return}l.info("[LSP] aceProject/onPackageChangeFinish: success"),this.broadcastToClients(e)}handleAsyncResponse(e,t){l.info(`[LSP] handleAsyncResponse\uFF0C method: ${t}`);let n=e.params;if(!f(n)){l.warn("[LSP] aceProject/onAsyncHover message invalid");return}let i=n.requestId;if(typeof i!="number"){l.warn(`[LSP] ${t} requestId invalid`);return}this.requestCallbacks.emit(i,t,n)}handleForceOpenFile(e){if(!e){l.warn("[LSP] handleForceOpenFile, uri is empty");return}this.requestCallbacks.emit(e,g.DID_OPEN,[]),this.clear(e)}parseDiagnostics(e){let t=e.uri;if(!t){l.info("[LSP] publishDiagnostics uri is null");return}let n=e.version??-1;if(n===-1)return;let i=this.diagnosticMap.get(t);if(!i){l.info(`[LSP] Diagnostic cleared for uri: ${t}`);return}let o=e.diagnostics||[];o.length!==0?o.forEach(s=>{this.normalizeDiagnostic(s),i.addMessage(n,JSON.stringify(s))}):i.setReceivedType(n),i.hasReceivedAllTypes(r.EXPECTED_DIAGNOSTIC_TYPES)&&this.finalizeDiagnostic(t,g.PUBLISH_DIAGNOSTICS,i.getMessages())}normalizeDiagnostic(e){if(delete e.source,e.severity!==void 0){let t=typeof e.severity=="number"?e.severity:parseInt(e.severity),n={1:"Error",2:"Warning",3:"Information",4:"Hint"};e.severityStr=n[t]||"Unknown",e.severity=e.severityStr}e.range&&(this.adjustPositionLine(e.range,"start"),this.adjustPositionLine(e.range,"end"))}adjustPositionLine(e,t){let n=e[t];n&&typeof n.line=="number"&&(n.line=n.line+1)}registerDiagnosticTimeout(e,t){this.requestCallbacks.registerTimeout(e,t,r.DIAGNOSTIC_TIMEOUT_MS,()=>{let n=this.diagnosticMap.get(e),i=n?n.getMessages():[];this.finalizeDiagnostic(e,t,i,i.length>0?void 0:`received no diagnostics within ${r.DIAGNOSTIC_TIMEOUT_MS}ms from LSP, uri: ${e}`)})}finalizeDiagnostic(e,t,n,i){let o={uri:e,diagnostics:n,...i?{errorMessage:i}:{}};this.requestCallbacks.emit(e,t,o),this.diagnosticMap.get(e)?.clear()}getPendingDiagnosticUris(){return Array.from(this.diagnosticMap.keys()).filter(e=>this.requestCallbacks.hasCallback(e))}cleanupDiagnosticState(e){this.requestCallbacks.clear(e),this.diagnosticMap.delete(e)}};import Ln from"path";import*as Sn from"path";var fn=class{enableRecentlyUsed=!1;enableCompletionSortByType=!0;maxValidCompletionItemsCount=50;enableCompletionFunctionParameter=!1;enableIndexModuleRootDirEtsFile=!1};var gn=class{overriddenEnable=!0;overridingEnable=!0;implementedEnable=!0;implementingEnable=!0};var yn=class{tsVariablesEnable=!1;tsPropertyEnable=!1;tsParameterEnable=!1;tsReturnEnable=!1;etsVariablesEnable=!1;etsPropertyEnable=!1;etsParameterEnable=!1;etsReturnEnable=!1};var vn=class{etsParameterNameHintKind=null;tsParameterNameHintKind=null};var wn=class{typeSetting=new yn;parameterNames=new vn};var bn=class{constructor(e,t,n,i){this.rootUri=e;this.lspServerWorkspacePath=F(Sn.dirname(t)),this.indexingDataLocation=F(i),this.loggerPath=F(Sn.join(n,"lspLog"))}rootUri;modules=[];clientType="intellij";indexingDataLocation="";completionSortSetting=new fn;gutterIconsSetting=new gn;inlayHintsSetting=new wn;lspMaxOldSpaceSize="8192";projectType="OHOS";loggerPath="";lspServerWorkspacePath};import*as Ds from"path";var It=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(F(Ds.join(e,"src","main","resources")))}};var Fd="OS",Qe=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${Fd}`;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 It(e)):this.buildProfileParam=new It}toString(){return JSON.stringify(this)}};var et=class{constructor(e=[]){this.pages=e}pages;pagesFileName="main_pages.json";metaDataList=[]};import*as W from"path";import*as rt from"fs";var Pn=class{modulePath;dependencies={};dynamicDependencies={}};var Ne=class{registryType;resolved;name;version;type;constructor(e){let t=typeof e=="object"&&e!==null?e:{};this.name=typeof t.name=="string"?t.name:"",this.version=typeof t.version=="string"?t.version:"",typeof t.registryType=="string"?this.registryType=t.registryType:this.registryType=typeof t.path=="string"?"local":"ohpm",typeof t.resolved=="string"?this.resolved=t.resolved:typeof t.storePath=="string"?this.resolved=t.storePath:this.resolved="",this.type=typeof t.type=="string"?t.type:void 0}};var tt=class{constructor(e,t,n){this.projectPath=e;this.moduleName=t;this.modulePath=n}projectPath;moduleName;modulePath;dependencies=[];devDependencies=[];dynamicDependencies=[];finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[]};import*as me from"path";import*as En from"fs";var nt=class{name="";version="";storePath="";dependencyPath="";path=""};var I={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:"oh-package.json5"},Ct=`${I.HVIGOR_CACHE}/${I.DEPENDENCY}`,Le=`${I.DEPENDENCY}${I.JSON5}`;var At=class r{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,n){let i=this.PACKAGE_JSON_PARSER_MAP.get(e);return i||(i=new r(e,t,n),this.PACKAGE_JSON_PARSER_MAP.set(e,i)),i}constructor(e,t,n){this.dependencyPath=e,this.modulePath=t,this.projectPath=n,this.fileSpecPattern=r.isWindows()?/^(?:[.]|~[/]|[/\\]|[a-zA-Z]:)/:/^(?:[.]|~[/]|[/]|[a-zA-Z]:)/}static isWindows(){return process.platform==="win32"}parseDependency(e){let t=me.join(this.dependencyPath,I.OH_PACKAGE_JSON5),n=Y(t);n&&(this.dependencies=this.getDependencyList(n,I.KEY_DEPENDENCY),this.devDependencies=this.getDependencyList(n,I.KEY_DEV_DEPENDENCY),this.dynamicDependencies=this.getDependencyList(n,I.KEY_DYNAMIC_DEPENDENCY),e.dependencies=this.dependencies,e.dynamicDependencies=this.devDependencies,e.devDependencies=this.dynamicDependencies)}getDependencyList(e,t){let n=[];if(!f(e))return n;let i=e[t];if(!f(i))return n;for(let[o,s]of Object.entries(i)){if(typeof s!="string"){l.error(`${o} package dependency value is not String ${t}`);continue}let a=new nt;a.name=o;let c=s.replace(/\s/g,"");a.version=c,c.startsWith(r.PARAMETER_PREFIX)||this.parseDependencyPath(o,c,a,!1),n.push(a)}return n}parseDependencyPath(e,t,n,i){if(!(!e||!t))try{let o=me.normalize(me.join(this.modulePath,I.OH_MODULES_PATH,e));if(!(t.startsWith(r.FILE_DEPENDENCY_PREFIX)||this.fileSpecPattern.test(t))){n.dependencyPath=o;return}if(n.path=t,this.fileNameForOhpm.test(t)){n.dependencyPath=o;return}let s=t;if(t.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(s=t.substring(r.FILE_DEPENDENCY_PREFIX.length)),me.isAbsolute(s)){n.dependencyPath=o;return}i||(o=me.normalize(me.join(this.modulePath,s))),En.existsSync(o)&&En.statSync(o).isDirectory()&&(n.dependencyPath=o)}catch(o){l.error("parser dependency path is invalid",o)}}};import*as kt from"fs";import*as De from"path";import $d from"json5";var Dn=class r{projectPath;static FILE_DEPENDENCY_PREFIX="file:";fileNameForOhpm=/[.](?:har|tgz|tar.gz|tar)$/;finalDependencies=[];finalDevDependencies=[];finalDynamicDependencies=[];storePathMap=new Map;constructor(e=""){this.projectPath=e}parseDependencies(e){let t=this.getLockFilePath(),n=this.readLockFile(t);if(!n)return!1;let i=this.validateLockFile(n);return i.valid?(this.extractDependencies(i.modules,i.packages,e),!0):!1}getLockFilePath(){return De.join(this.projectPath,I.OH_MODULES_PATH,I.OHPM_PATH,I.LOCK_JSON5_FILE)}readLockFile(e){if(!kt.existsSync(e))return l.error("lock file does not exist"),this.clearDependencies(),null;try{let t=kt.readFileSync(e,"utf8"),n=$d.parse(t);return n||(l.error("lockFileJsonObject is null"),this.clearDependencies(),null)}catch(t){return l.error("Error parsing lock.json5:",t),this.clearDependencies(),null}}validateLockFile(e){if(!f(e))return l.error("lockFileJsonObject is not a valid object"),this.clearDependencies(),{valid:!1};let t=e.modules;if(!t)return l.error("modulesJsonObject is null"),this.clearDependencies(),{valid:!1};let n=e.packages;return n?{valid:!0,modules:t,packages:n}:(l.error("packagesJsonObject is null"),this.clearDependencies(),{valid:!1})}extractDependencies(e,t,n){this.storePathMap=this.parseStorePathMap(t),this.finalDependencies=this.getDependencyList(e,I.KEY_DEPENDENCY,n),this.finalDevDependencies=this.getDependencyList(e,I.KEY_DEV_DEPENDENCY,n),this.finalDynamicDependencies=this.getDependencyList(e,I.KEY_DYNAMIC_DEPENDENCY,n)}parseStorePathMap(e){let t=new Map;if(!f(e))return t;for(let[n,i]of Object.entries(e)){if(!f(i)){l.error(`${n} value is not json object`);continue}typeof i.storePath=="string"&&t.set(n,i.storePath)}return t}getDependencyList(e,t,n){if(!f(e))return[];for(let[i,o]of Object.entries(e))if(f(o)){let s=typeof o.name=="string"?o.name:"";if(n==="."&&s===""||s===n)return this.getFinalDependencyList(e,t,i)}return[]}getFinalDependencyList(e,t,n){let i=e[n];if(!f(i))return l.error("moduleJsonObject is null"),[];let o=[],s=i[t];if(!f(s))return[];for(let[a,c]of Object.entries(s)){if(!f(c))continue;let d=typeof c.specifier=="string"?c.specifier:"",u=typeof c.version=="string"?c.version:"",b=new nt;b.name=a,b.version=u.startsWith(r.FILE_DEPENDENCY_PREFIX)?u.substring(r.FILE_DEPENDENCY_PREFIX.length):u,this.parseDependencyPath(b,n,a,d,u);let k=`${a}@${u}`;this.storePathMap.has(k)&&(b.storePath=this.storePathMap.get(k)||""),o.push(b)}return o}parseDependencyPath(e,t,n,i,o){let s=De.normalize(De.join(this.projectPath,t,I.OH_MODULES_PATH,n));try{let a=o;o.startsWith(r.FILE_DEPENDENCY_PREFIX)&&(a=o.substring(r.FILE_DEPENDENCY_PREFIX.length));let c=a;if(De.isAbsolute(c)||(c=De.join(this.projectPath,a)),!kt.existsSync(c)){e.dependencyPath=s;return}if(e.path=i,this.fileNameForOhpm.test(o)){e.dependencyPath=s;return}e.dependencyPath=c}catch(a){l.error("Invalid dependency path in lock.json5",a)}}clearDependencies(){this.finalDependencies=[],this.finalDevDependencies=[],this.finalDynamicDependencies=[]}};var He=class{constructor(e){this.projectRoot=e}projectRoot;getAllModuleInfo(){let e=Ps(this.projectRoot);try{let t=Y(e);if(typeof t!="object"||t===null)return[];let n=t.modules;return Array.isArray(n)?n.filter(i=>{if(typeof i!="object"||i===null)return!1;let o=i;return typeof o.name=="string"&&typeof o.srcPath=="string"}):[]}catch(t){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${t instanceof Error?t.message:String(t)}`),[]}}};function Is(r){return f(r)?typeof r.name=="string"&&typeof r.srcPath=="string":!1}var Tt=class{constructor(e,t){this.projectPath=e;this.sdkPath=t;this.moduleInfoParse=new He(this.projectPath)}projectPath;sdkPath;moduleInfoParse;getAllDependencyMap(e){let t=this.projectPath,n=W.join(t,Ct),i=W.join(n,Le);if(!rt.existsSync(n)||!rt.existsSync(i)){let a="Dependency map or JSON not found";return l.warn(`[Parser] getAllDependencyMap failed: ${a}.`),{status:"ERROR",message:`${a}, please rebuild project`}}let o=new tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(n,o),this.parseLockJson(o);let s=this.moduleInfoParse.getAllModuleInfo();if(s.length===0){let a="No modules found in build-profile.json5";return l.warn(`[Parser] getAllDependencyMap failed: ${a}.`),{status:"ERROR",message:a}}for(let a of s)Is(a)&&this.parseSingleModule(a,n,o,e);return{status:"OK"}}getDependenciesOnly(e){let t=[],n=this.projectPath,i=W.join(n,Ct),o=W.join(i,Le);if(!rt.existsSync(i)||!rt.existsSync(o))return l.warn("[Parser] Dependency map or JSON not found."),t;let s=e&&e.length>0?new Set(e.map(d=>d.trim()).filter(Boolean)):null,a=new tt(this.projectPath,".",this.projectPath);this.parseProjectDependencies(i,a),this.parseLockJson(a);let c=this.moduleInfoParse.getAllModuleInfo();if(c.length===0)return l.warn("[Parser] getAllDependencyMap failed: No modules found in build-profile.json5."),t;for(let d of c){if(!Is(d))continue;let u=d.name;if(s&&!s.has(u))continue;let b=d.srcPath,k=W.resolve(this.projectPath,b),ce=W.join(i,u),je=F(k),Fe=this.buildModuleDependencies(u,je,ce,a);Fe.moduleName=u,t.push(Fe)}return t}parseSingleModule(e,t,n,i){let o=e.name,s=e.srcPath,a=W.resolve(this.projectPath,s),c=W.join(t,o),d=F(a),u=new Qe(d),b=this.buildModuleDependencies(o,d,c,n);this.parseModuleJson5(d,u);let k=this.parseMainPages(d);this.parseSdkJson(u),this.parseCompatibleSdkVersion(u),u.moduleName=o,u.moduleType=o,u.packageName=o,u.moduleDependencies=b,u.moduleJsonParam=new et(k),i.push(u)}buildModuleDependencies(e,t,n,i){let o=new tt(this.projectPath,e,t);At.getInstance(n,t,this.projectPath).parseDependency(o),this.parseLockJson(o),o.finalDependencies.push(...i.finalDependencies),o.finalDevDependencies.push(...i.finalDevDependencies),o.finalDynamicDependencies.push(...i.finalDynamicDependencies),o.finalDependencies.push(...o.finalDevDependencies);let a=new Pn;return a.modulePath=t,this.toModuleDependencies(o,a),a}toModuleDependencies(e,t){let n={},i={};for(let o of e.finalDependencies)n[o.name]=new Ne(o);for(let o of e.finalDynamicDependencies)i[o.name]=new Ne(o);t.dependencies=n,t.dynamicDependencies=i}parseProjectDependencies(e,t){let n=W.join(e,I.OH_PACKAGE_JSON5);if(!rt.existsSync(n))return;At.getInstance(e,this.projectPath,this.projectPath).parseDependency(t)}parseLockJson(e){let t=new Dn(e.projectPath);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)}parseModuleJson5(e,t){let n=W.join(e,"src","main","module.json5"),i=Y(n);if(!f(i)||!f(i.module))return;let o=i.module;t.permissions=this.parseRequestPermissions(o),t.deviceType=this.parseDeviceTypes(o)}parseRequestPermissions(e){let t=[];if(f(e)&&Array.isArray(e.requestPermissions))for(let n of e.requestPermissions)f(n)&&typeof n.name=="string"&&t.push(n.name);return t}parseMainPages(e){let t=W.join(e,"src","main","resources","base","profile","main_pages.json"),n=Y(t);return!f(n)||!Array.isArray(n.src)?[]:n.src.filter(i=>typeof i=="string")}parseSdkJson(e){let t=W.join(this.sdkPath,"default","sdk-pkg.json"),n=Y(t);!f(n)||!f(n.data)||(typeof n.data.apiVersion=="string"&&(e.compileSdkLevel=n.data.apiVersion),typeof n.data.releaseType=="string"&&(e.compileSdkType=n.data.releaseType),typeof n.data.version=="string"&&(e.compileSdkVersion=n.data.version))}parseCompatibleSdkVersion(e){let t=W.join(this.projectPath,"build-profile.json5"),n=Y(t);if(!f(n)||!f(n.app)||!Array.isArray(n.app.products)||n.app.products.length===0)return;let i=n.app.products[0];if(!f(i)||typeof i.compatibleSdkVersion!="string")return;let[o,s]=this.parseBySplit(i.compatibleSdkVersion);e.compatibleSdkVersion=o,e.compatibleSdkLevel=s}parseBySplit(e){let t=e.indexOf("(");if(t===-1||!e.endsWith(")"))return[e,""];let n=e.substring(0,t),i=e.substring(t+1,e.length-1);return[n,i]}parseDeviceTypes(e){return!f(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 In=class{constructor(e=[]){this.valueSet=e}valueSet};var it=class{refreshSupport=!0;tokenTypes=["namespace","type","class","enum","interface","struct","parameter","variable","property","function","method"];tokenModifiers=["declaration","definition","readonly","static","deprecated"]};var Cs=(y=>(y[y.File=1]="File",y[y.Module=2]="Module",y[y.Namespace=3]="Namespace",y[y.Package=4]="Package",y[y.Class=5]="Class",y[y.Method=6]="Method",y[y.Property=7]="Property",y[y.Field=8]="Field",y[y.Constructor=9]="Constructor",y[y.Enum=10]="Enum",y[y.Interface=11]="Interface",y[y.Function=12]="Function",y[y.Variable=13]="Variable",y[y.Constant=14]="Constant",y[y.String=15]="String",y[y.Number=16]="Number",y[y.Boolean=17]="Boolean",y[y.Array=18]="Array",y[y.Object=19]="Object",y[y.Key=20]="Key",y[y.Null=21]="Null",y[y.EnumMember=22]="EnumMember",y[y.Struct=23]="Struct",y[y.Event=24]="Event",y[y.Operator=25]="Operator",y[y.TypeParameter=26]="TypeParameter",y))(Cs||{}),As=()=>Object.values(Cs).filter(r=>typeof r=="number");var Cn=class{documentChanges=null;resourceOperations=null;failureHanding=null;normalizesLineEndings=null;changeAnnotationSupport=null};var An=class{applyEdit=!0;workspaceEdit=new Cn;didChangeConfiguration=null;didChangeWatchedFiles={relativePatternSupport:{},dynamicRegistration:{}};symbol=new In(As());executeCommand={dynamicRegistration:{}};workspaceFolders=!1;configuration=!1;semanticTokens=new it;codeLens=null;fileOperations=null;inlayHint=null;diagnostics=null};var kn=class{willSave=!0;willSaveWaitUntil=!0;didSave=!0;dynamicRegistration=null};var Tn=class{constructor(e=[]){this.valueSet=e}valueSet};var Mn=class{snippetSupport=!0;commitCharactersSupport=null;documentationFormat=null;deprecateSupport=null;preselectSupport=null;tagSupport=null;insertReplaceSupport=null;resolveSupport=null;insertTextModeSupport=null;labelDetailsSupport=null};var ks=(v=>(v[v.Text=1]="Text",v[v.Method=2]="Method",v[v.Function=3]="Function",v[v.Constructor=4]="Constructor",v[v.Field=5]="Field",v[v.Variable=6]="Variable",v[v.Class=7]="Class",v[v.Interface=8]="Interface",v[v.Module=9]="Module",v[v.Property=10]="Property",v[v.Unit=11]="Unit",v[v.Value=12]="Value",v[v.Enum=13]="Enum",v[v.Keyword=14]="Keyword",v[v.Snippet=15]="Snippet",v[v.Color=16]="Color",v[v.File=17]="File",v[v.Reference=18]="Reference",v[v.Folder=19]="Folder",v[v.EnumMember=20]="EnumMember",v[v.Constant=21]="Constant",v[v.Struct=22]="Struct",v[v.Event=23]="Event",v[v.Operator=24]="Operator",v[v.TypeParameter=25]="TypeParameter",v))(ks||{}),Ts=()=>Object.values(ks).filter(r=>typeof r=="number");var xn=class{completionItemKind=new Tn(Ts());completionItem=new Mn;contextSupport=null;insertTextSupport=null;completionList=null;dynamicRegistration=null};var Rn=class{synchronization=new kn;completion=new xn;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 it;moniker=null;linkedEditingRange=null;inlayHint=null;inlineValue=null;diagnostic=null};var On=class{workspace=new An;textDocument=new Rn;notebookDocument=null;window=null;general=null;experimental=null};var Nn=class{constructor(e,t,n){this.rootUri=e;this.initializationOptions=t;this.capabilities=n}rootUri;initializationOptions;capabilities};function ot(r){return f(r)?typeof r.line=="number"&&typeof r.character=="number":!1}function Ms(r){return f(r)?typeof r.uri=="string"&&typeof r.text=="string"&&typeof r.languageId=="string"&&typeof r.version=="number":!1}function xs(r){if(!f(r)||typeof r.text!="string")return!1;let e=r.range;return f(e)?ot(e.start)&&ot(e.end):!1}var Hn=class{constructor(e,t,n,i,o){this.sdkPath=e;this.rootUri=n;this.nodeMaxOldSpaceSize=o;this.serverPath=Ln.resolve(t,"ace-server","out","index.js"),this.logPath=Ss(),this.indexLogPath=i||this.logPath,this.messageHandle=new mn({serverPath:this.serverPath,logPath:this.logPath,nodeMaxOldSpaceSize:this.nodeMaxOldSpaceSize,indexingDataLocation:this.indexLogPath}),this.messageHandle.setBroadcastToClients(s=>this.onLspMessage(s))}sdkPath;rootUri;nodeMaxOldSpaceSize;messageHandle;serverPath;logPath;lastStartErrorMessage=null;currentParams=null;indexLogPath;lastDepsOnlyForDiff=[];get currentModuleModels(){return this.currentParams?.initializationOptions?.modules??[]}initTimeoutMs=60*1e3;async start(e,t){let n=!1;try{l.info(`serverPath: ${this.serverPath}`),l.info(`rootUri: ${this.rootUri}`),l.info(`sdkPath: ${this.sdkPath}`),l.info(`logPath: ${this.logPath}`),await this.messageHandle.start();let i=he(this.rootUri),o=new bn(i,this.serverPath,this.logPath,this.indexLogPath),s=[],c=new Tt(this.rootUri,this.sdkPath).getAllDependencyMap(s);if(c.status==="ERROR")throw new Error(`${c.message}`);this.fillModuleModelsPaths(s),o.modules=s,this.currentParams=new Nn(i,o,new On),this.messageHandle.sendInitialize(this.currentParams,1),this.messageHandle.onIndexingProgressUpdate(()=>{this.onLspMessage({jsonrpc:M,method:g.ARKTS_INDEXING_PROGRESS,params:{}})}),await this.withResettableTimeout((d,u)=>{this.messageHandle.onIndexingProgressUpdate(u),this.messageHandle.onInitializationCompleted(d)},"LSP initialization",this.initTimeoutMs),this.messageHandle.sendInitialized(e),n=!0}catch(i){this.lastStartErrorMessage=i instanceof Error?i.message:String(i),l.error(`[LSP] Initialization failed: ${this.lastStartErrorMessage}`),await this.messageHandle.stop()}t?.(n)}consumeStartErrorMessage(){let e=this.lastStartErrorMessage;return this.lastStartErrorMessage=null,e}onLspMessage=()=>{};setOnMessage(e){this.onLspMessage=e}registerDiagnosticCallback(e){let t=he(e);this.messageHandle.registerRequestCallback(t,(n,i)=>{let o=f(i)?i:{};l.info(`[LSP] onDiagnosticCompleted called, filePath: ${e}`);let s={jsonrpc:M,method:n,params:{uri:typeof o.uri=="string"?o.uri:t,diagnostics:Array.isArray(o.diagnostics)?o.diagnostics.filter(a=>typeof a=="string"):[],...typeof o.errorMessage=="string"?{errorMessage:o.errorMessage}:{}}};this.onLspMessage(s)})}registerRequestCallback(e,t){this.messageHandle.registerRequestCallback(t,(n,i)=>{l.info(`[LSP] onRequestCompleted called, requestId: ${t}, method: ${n}`);let o={jsonrpc:M,id:e,result:f(i)?i.result:void 0};this.onLspMessage(o)})}reloadDependenciesOnly(e){let t=e?.fullReload??!1,n=new Tt(this.rootUri,this.sdkPath),i=this.getModuleModelsByName();if(t){l.info("[LspServerProxy] Project-level oh-package changed, parsing all modules' dependencies");let d=n.getDependenciesOnly();this.markDependencyTypesIncremental(d);let u=this.mergeDepsOnlyIntoModuleList(d,i);return this.applyModuleModelsUpdate(u),l.info(`[LspServerProxy] Dependencies only (all) reloaded, count: ${u.length}`),this.lastDepsOnlyForDiff=d,d}let o=e?.changedModules??[],s=new Set(e?.removedModuleNames??[]);if(o.length===0&&s.size===0)return l.info("[LspServerProxy] No changed/removed modules, skip dependency reload"),[];l.info(`[LspServerProxy] Module-level deps changed, parsing: [${o.join(", ")}]`);let a=n.getDependenciesOnly(o);this.markDependencyTypesIncremental(a);let c=this.mergeIncrementalDeps(this.currentModuleModels,s,a);return this.applyModuleModelsUpdate(c),l.info(`[LspServerProxy] Dependencies only (incremental) reloaded, count: ${c.length}`),this.lastDepsOnlyForDiff=a,a}getModuleModelsByName(){return new Map(this.currentModuleModels.map(e=>[e.moduleName??"",e]))}markDependencyTypesIncremental(e){let t=this.getModuleModelsByName(),n=new Map(this.lastDepsOnlyForDiff.map(i=>[i.moduleName??"",i]));for(let i of e){let o=i.moduleName??"",{oldDeps:s,oldDynamic:a}=this.getOldDepsForModule(o,t,n),c=i.dependencies??{},d=i.dynamicDependencies??{};this.markAddAndDeleteInDeps(s,c,(u,b)=>{(i.dependencies??={})[u]=this.makeDeleteEntry(u,b)}),this.markAddAndDeleteInDeps(a,d,(u,b)=>{(i.dynamicDependencies??={})[u]=this.makeDeleteEntry(u,b)})}}getOldDepsForModule(e,t,n){let i=t.get(e),o=i?.moduleDependencies?.dependencies??{},s=i?.moduleDependencies?.dynamicDependencies??{};if(Object.keys(o).length===0&&Object.keys(s).length===0){let a=n.get(e);a&&(o=a.dependencies??{},s=a.dynamicDependencies??{})}return{oldDeps:o,oldDynamic:s}}markAddAndDeleteInDeps(e,t,n){for(let i of Object.keys(t))i in e||(t[i].type="add");for(let i of Object.keys(e))i in t||n(i,e[i])}makeDeleteEntry(e,t){return new Ne({name:e,version:t?.version??"",registryType:t?.registryType??"ohpm",resolved:t?.resolved??"",type:"delete"})}createMinimalModelFromDepsItem(e){let t=new Qe(e.modulePath);return t.moduleName=e.moduleName,t.moduleType=e.moduleName,t.packageName=e.moduleName,t.moduleJsonParam=new et([]),t.modulePath=e.modulePath,t.moduleDependencies=e,t}mergeDepsOnlyIntoModuleList(e,t){let n=[];for(let i of e){let o=i.moduleName??"",s=t.get(o);s?(s.modulePath=i.modulePath,s.moduleDependencies=i):s=this.createMinimalModelFromDepsItem(i),n.push(s)}return n}mergeIncrementalDeps(e,t,n){let i=new Map(n.map(s=>[s.moduleName??"",s])),o=[];for(let s of e){let a=s.moduleName??"";if(t.has(a))continue;let c=i.get(a);c&&(s.modulePath=c.modulePath,s.moduleDependencies=c,i.delete(a)),o.push(s)}for(let[,s]of i)o.push(this.createMinimalModelFromDepsItem(s));return o}applyModuleModelsUpdate(e){this.fillModuleModelsPaths(e),this.currentParams&&(this.currentParams.initializationOptions.modules=e)}fillModuleModelsPaths(e){let t=this.sdkPath,n=cn(Ln.join(t,"default/openharmony/ets/build-tools/ets-loader")),i=cn(Ln.join(t,"default/openharmony/ets/api")),o=cn(Ln.join(t,"default/hms"));for(let s of e)s.aceLoaderPath=n,s.sdkJsPath=i,s.hosSdkPath=o}sendRequest(e){switch(e.method){case g.HOVER:this.handleHoverRequest(e);break;case g.DEFINITION:this.handleDefinitionRequest(e);break;case g.REFERENCES:this.handleReferencesRequest(e);break;default:l.warn(`Unhandled LSP request: ${e.method}`)}}handleHoverRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/hover, params missing or not an object");return}let{textDocument:n,position:i,requestId:o}=t;if(!f(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/hover, malformed or missing required parameters");return}if(typeof o!="number"){l.error("Invalid client textDocument/hover, requestId missing or not a number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_HOVER,t,o,K.ON_ASYNC_HOVER)}handleDefinitionRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/definition, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!f(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/definition, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/definition, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_DEFINITION,t,o,K.ON_ASYNC_DEFINITION)}handleReferencesRequest(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/references, params missing or not an object");return}let{textDocument:n,position:i}=t;if(!f(n)||typeof n.uri!="string"||!ot(i)){l.error("Invalid client textDocument/references, malformed or missing required parameters");return}let o=this.resolveRequestId(t.requestId,e.id);if(!Number.isFinite(o)){l.error("Invalid client textDocument/references, requestId missing or not a valid number");return}this.registerRequestCallback(e.id,o),this.messageHandle.sendAsyncRequest(g.ON_ASYNC_FIND_USAGES,t,o,K.ON_ASYNC_FIND_USAGES)}resolveRequestId(e,t){let n=e??t;return typeof n=="number"?n:Number(n)}sendNotification(e){if(!vs(e)){l.info("LspServerProxy, msg is not notification request, ignore.");return}switch(e.method){case g.DID_OPEN:this.handleDidOpenNotification(e);break;case g.DID_CHANGE:this.handleDidChangeNotification(e);break;case g.DID_CLOSE:this.handleDidCloseNotification(e);break;case g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT:this.handleDidChangePackageDependencies(e);break;case g.WORKSPACE_DID_CHANGE_WATCHED_FILES:this.handleDidChangeWatchedFiles(e);break;default:l.warn(`Unhandled LSP notification: ${e.method}`)}}handleDidOpenNotification(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/didOpen, params missing or not an object");return}let{textDocument:n,editorFiles:i}=t;if(!Ms(n)||!zr(i)){l.error("Invalid client textDocument/didOpen, malformed or missing required parameters");return}let s={isFromEditor:typeof t.isFromEditor=="boolean"?t.isFromEditor:!1,editorFiles:i,textDocument:n};this.registerDiagnosticCallback(n.uri),this.messageHandle.onAsyncOpenFile(s)}handleDidChangeNotification(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/didChange, params missing or not an object");return}let{textDocument:n,contentChanges:i}=t;if(!f(n)||typeof n.uri!="string"||typeof n.version!="number"){l.error("Invalid client textDocument/didChange, malformed or missing required parameters");return}if(!Array.isArray(i)||!i.every(xs)){l.error("Invalid client textDocument/didChange, contentChanges invalid");return}let o=n.uri,s=n.version;this.registerDiagnosticCallback(o),this.messageHandle.onAsyncDidChange({uri:o,version:s,contentChanges:i})}handleDidCloseNotification(e){let t=e.params;if(!f(t)){l.error("Invalid client textDocument/didClose, params missing or not an object");return}let{textDocument:n}=t;if(!f(n)||typeof n.uri!="string"){l.error("Invalid client textDocument/didClose, malformed or missing required parameters");return}let i=typeof t.isManual=="boolean"?t.isManual:!1;this.messageHandle.closeFile(n.uri,i)}handleDidChangePackageDependencies(e){let t=e.params;if(!f(t)){l.error("Invalid client aceProject/onDidChangePakcageDependencies, params missing or not an object");return}let{moduleSet:n}=t;if(!Array.isArray(n)||n.length===0){l.error("Invalid client aceProject/onDidChangePakcageDependencies, malformed or missing required parameters");return}this.messageHandle.sendModuleDependencyUpdate(t)}handleDidChangeWatchedFiles(e){let t=e.params;if(!f(t)){l.error("Invalid client workspace/didChangeWatchedFiles, params missing or not an object");return}let{changes:n}=t;if(!Array.isArray(n)){l.error("Invalid client workspace/didChangeWatchedFiles, malformed or missing required parameters");return}this.messageHandle.onDidChangeWatchedFiles(n)}withResettableTimeout(e,t,n){return new Promise((i,o)=>{let s,a=()=>{s=setTimeout(()=>{o(new Error(`${t} timeout after ${n}ms`))},n)},c=()=>{clearTimeout(s),a()};a(),e(()=>{clearTimeout(s),i()},c)})}async dispose(){await this.messageHandle.stop()}};import*as fe from"fs";import*as V from"path";import{createHash as _d}from"crypto";import{EventEmitter as Wd}from"events";var jn=class extends Wd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n}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()),n=new Set(this.watchers.keys());for(let i of t)n.has(i)||(this.watchFile(i),l.info(`[ConfigFileWatcher] Started watching: ${i}`));for(let i of n)t.has(i)||(this.unwatchFile(i),l.info(`[ConfigFileWatcher] Stopped watching: ${i}`));l.info(`[ConfigFileWatcher] Watching ${this.watchers.size} oh-package.json5 file(s)`)}watchBuildProfile(){let t=this.getBuildProfilePath();if(!fe.existsSync(t)){l.warn(`[ConfigFileWatcher] build-profile.json5 not found at ${t}, cannot watch for module changes`);return}try{this.buildProfileWatcher=fe.watch(t,n=>{n==="change"&&this.onBuildProfileChanged()}),this.buildProfileWatcher.on("error",n=>{l.error(`[ConfigFileWatcher] build-profile.json5 watch error: ${n.message}`)}),l.info(`[ConfigFileWatcher] Watching module registry: ${t}`)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch build-profile.json5: ${n instanceof Error?n.message:String(n)}`)}}emitModuleAddedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:1,filePath:o,relativePath:i.srcPath,timestamp:n,moduleName:i.name})}}emitModuleRemovedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.srcPath);this.emit("configChanged",{source:"buildProfile",kind:2,filePath:o,relativePath:i.srcPath,timestamp:n,removedModuleName:i.name})}}emitModuleRenamedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:3,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name,removedModuleName:i.before.name})}}emitModuleMovedEvents(t,n){for(let i of t){let o=V.resolve(this.projectRoot,i.after.srcPath);this.emit("configChanged",{source:"buildProfile",kind:6,filePath:o,relativePath:i.after.srcPath,timestamp:n,moduleName:i.after.name})}}processBuildProfileDiff(t){this.refreshWatchTargets();let n=Date.now();this.emitModuleAddedEvents(t.added,n),this.emitModuleRemovedEvents(t.removed,n),this.emitModuleRenamedEvents(t.renamed,n),this.emitModuleMovedEvents(t.moved,n)}onBuildProfileChanged(){let t="__build_profile__",n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.parseModulesFromBuildProfile(),s=this.computeModulesSnapshot(o);if(s===this.lastModulesSnapshot){l.info("[ConfigFileWatcher] build-profile.json5 changed but modules unchanged, skipping");return}let a=this.diffModules(this.lastModules,o);this.lastModules=o,this.lastModulesSnapshot=s,l.info(`[ConfigFileWatcher] build-profile.json5 modules changed, added=${a.added.length}, removed=${a.removed.length}, renamed=${a.renamed.length}, moved=${a.moved.length}`),this.processBuildProfileDiff(a)},this.debounceMs);this.debounceTimers.set(t,i)}computeModulesSnapshot(t){return t.map(i=>`${i.name}::${i.srcPath}`).sort().join("|")}diffModules(t,n){let i=this.buildModuleMatchState(n),o={added:[],removed:[],renamed:[],moved:[]};return this.matchExactModules(t,i),this.matchRenamedModules(t,i,o),this.matchMovedModules(t,i,o),this.collectRemovedModules(t,i,o),this.collectAddedModules(n,i,o),o}buildModuleMatchState(t){let n=new Map,i=new Map;for(let o of t)n.set(o.srcPath,o),i.set(o.name,o);return{matchedOld:new Set,matchedNew:new Set,newBySrc:n,newByName:i}}matchExactModules(t,n){for(let i of t){let o=n.newBySrc.get(i.srcPath);o&&o.name===i.name&&(n.matchedOld.add(i),n.matchedNew.add(o))}}matchRenamedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newBySrc.get(o.srcPath);s&&!n.matchedNew.has(s)&&s.name!==o.name&&(i.renamed.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}matchMovedModules(t,n,i){for(let o of t){if(n.matchedOld.has(o))continue;let s=n.newByName.get(o.name);s&&!n.matchedNew.has(s)&&s.srcPath!==o.srcPath&&(i.moved.push({before:o,after:s}),n.matchedOld.add(o),n.matchedNew.add(s))}}collectRemovedModules(t,n,i){for(let o of t)n.matchedOld.has(o)||i.removed.push(o)}collectAddedModules(t,n,i){for(let o of t)n.matchedNew.has(o)||i.added.push(o)}parseModulesFromBuildProfile(){let t=this.getBuildProfilePath();try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[ConfigFileWatcher] Failed to parse build-profile.json5: ${n instanceof Error?n.message:String(n)}`),[]}}collectWatchTargets(){let t=[],n=V.join(this.projectRoot,I.OH_PACKAGE_JSON5);fe.existsSync(n)&&t.push(n);let i=this.parseModulesFromBuildProfile();for(let o of i){let s=V.resolve(this.projectRoot,o.srcPath),a=V.join(s,I.OH_PACKAGE_JSON5);fe.existsSync(a)&&t.push(a)}return t}getBuildProfilePath(){return V.join(this.projectRoot,"build-profile.json5")}computeFileHash(t){try{let n=fe.readFileSync(t,"utf-8");return _d("sha256").update(n).digest("hex")}catch{return null}}watchFile(t){if(!this.watchers.has(t))try{let n=this.computeFileHash(t);n&&this.contentHashes.set(t,n);let i=fe.watch(t,o=>{o==="change"&&this.onFileChanged(t)});i.on("error",o=>{l.error(`[ConfigFileWatcher] Watch error for ${t}: ${o.message}`)}),this.watchers.set(t,i)}catch(n){l.error(`[ConfigFileWatcher] Failed to watch ${t}: ${n instanceof Error?n.message:String(n)}`)}}unwatchFile(t){let n=this.watchers.get(t);n&&(n.close(),this.watchers.delete(t)),this.contentHashes.delete(t);let i=this.debounceTimers.get(t);i&&(clearTimeout(i),this.debounceTimers.delete(t))}onFileChanged(t){let n=this.debounceTimers.get(t);n&&clearTimeout(n);let i=setTimeout(()=>{this.debounceTimers.delete(t);let o=this.computeFileHash(t);if(!o){l.warn(`[ConfigFileWatcher] Could not read file for hash: ${t}`);return}if(this.contentHashes.get(t)===o){l.info(`[ConfigFileWatcher] File touched but content unchanged, skipping: ${t}`);return}this.contentHashes.set(t,o),l.info(`[ConfigFileWatcher] Config file content changed: ${t}`);let a={source:"ohPackage",kind:4,filePath:t,fileName:V.basename(t),relativePath:V.relative(this.projectRoot,t),timestamp:Date.now()};this.emit("configChanged",a)},this.debounceMs);this.debounceTimers.set(t,i)}stop(){for(let[,t]of this.watchers)t.close();this.watchers.clear(),this.buildProfileWatcher&&(this.buildProfileWatcher.close(),this.buildProfileWatcher=null);for(let t of this.debounceTimers.values())clearTimeout(t);this.debounceTimers.clear(),this.contentHashes.clear(),l.info("[ConfigFileWatcher] All watchers stopped")}};import*as Ie from"fs";import*as Q from"path";import{createHash as Ud}from"crypto";import{EventEmitter as Bd}from"events";var Fn=class extends Bd{constructor(t,n=500){super();this.projectRoot=t;this.debounceMs=n,this.coalesceMs=n+300,this.depMapDir=Q.join(t,Ct)}projectRoot;dirWatcher=null;contentHashes=new Map;lastModules=[];debounceMs;depMapDir;pendingTags=[];pendingRenames=[];coalesceTimer=null;coalesceMs;fullScanTimer=null;pollInterval=null;initialScanDone=!1;start(){if(!Ie.existsSync(this.depMapDir)){l.warn(`[DependencyMapWatcher] dependencyMap dir not found: ${this.depMapDir}, skip watching`);return}this.lastModules=this.parseModulesFromDepMap();try{this.dirWatcher=Ie.watch(this.depMapDir,{recursive:!0},(t,n)=>this.onDirEvent(t,n)),this.dirWatcher.on("error",t=>{l.error(`[DependencyMapWatcher] Directory watch error for ${this.depMapDir}: ${t.message}`)})}catch(t){l.error(`[DependencyMapWatcher] Failed to watch directory ${this.depMapDir}: ${t instanceof Error?t.message:String(t)}`);return}this.pollInterval=setInterval(()=>this.scanAllCacheFiles(),2500),l.info(`[DependencyMapWatcher] Started, watching directory (recursive): ${this.depMapDir}, modules: [${this.lastModules.map(t=>t.name).join(", ")}]`)}canonicalPath(t){return F(Q.resolve(t))}onDirEvent(t,n){if(!n||typeof n!="string")return;let i=n.replace(/\\/g,"/"),o;if(i===I.OH_PACKAGE_JSON5)o="root-oh-package";else if(i===Le)o="dep-map-json";else{let a=i.match(/^([^/]+)\/oh-package\.json5$/);o=a?`module:${a[1]}`:""}if(!o)return;let s=Q.join(this.depMapDir,n);Ie.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,l.info("[DependencyMapWatcher] All watchers stopped")}scheduleDebouncedFullScan(){this.fullScanTimer&&clearTimeout(this.fullScanTimer),this.fullScanTimer=setTimeout(()=>{this.fullScanTimer=null,this.scanAllCacheFiles()},this.debounceMs)}scanAllCacheFiles(){let t=Q.join(this.depMapDir,I.OH_PACKAGE_JSON5),n=Q.join(this.depMapDir,Le),i=this.parseModulesFromDepMap(),o=[{path:t,tag:"root-oh-package"},{path:n,tag:"dep-map-json"},...i.map(s=>({path:Q.join(this.depMapDir,s.name,I.OH_PACKAGE_JSON5),tag:`module:${s.name}`}))];for(let{path:s,tag:a}of o){if(!Ie.existsSync(s))continue;let c=this.canonicalPath(s),d=this.computeFileHash(s);if(!d)continue;let u=this.contentHashes.get(c);if(!this.initialScanDone){this.contentHashes.set(c,d);continue}u!==d&&(this.contentHashes.set(c,d),l.info(`[DependencyMapWatcher] Cache file changed: ${s} (tag=${a})`),this.scheduleCoalescedReload(a))}this.initialScanDone||(this.initialScanDone=!0)}parseModulesFromDepMap(){let t=Q.join(this.depMapDir,Le);try{let n=Y(t);if(typeof n!="object"||n===null)return[];let i=n.modules;return Array.isArray(i)?i.filter(o=>{if(typeof o!="object"||o===null)return!1;let s=o;return typeof s.name=="string"&&typeof s.srcPath=="string"}):[]}catch(n){return l.warn(`[DependencyMapWatcher] Failed to parse dependencyMap.json5: ${n instanceof Error?n.message:String(n)}`),[]}}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,n=this.pendingRenames;return this.pendingTags=[],this.pendingRenames=[],{tags:t,renameEntries:n}}processTagsIntoSets(t,n,i,o){for(let s of t)s.startsWith("module:")?(i.add(s.substring(7)),n.add("moduleDepsChanged")):s.startsWith("dep-added:")?(i.add(s.substring(10)),n.add("moduleAdded")):s.startsWith("dep-removed:")&&(o.add(s.substring(12)),n.add("moduleRemoved"))}processRenameEntries(t,n,i,o,s){for(let a of t)s.push(a.info),i.add(a.info.newName),o.add(a.info.oldName),n.add(a.kind)}buildAddedNamesSet(t,n){let i=new Set;for(let o of t)o.startsWith("dep-added:")&&i.add(o.substring(10));for(let o of n)i.add(o.info.newName);return i}emitIncrementalReload(t,n,i,o,s){l.info(`[DependencyMapWatcher] Coalesced \u2192 kinds=[${[...t].join(",")}], changed=[${[...n].join(",")}], removed=[${[...i].join(",")}], added=[${[...o].join(",")}], renames=[${s.map(a=>`${a.oldName}\u2192${a.newName}`).join(",")}]`),this.emit("reload",{fullReload:!1,kinds:[...t],changedModules:[...n],removedModuleNames:[...i],addedModuleNames:[...o],renames:s.length>0?s:void 0})}flushPendingReload(){let{tags:t,renameEntries:n}=this.collectPendingState();if(t.length===0&&n.length===0)return;if(l.info(`[DependencyMapWatcher] Flushing coalesced reload, tags=[${t.join(", ")}], renames=${n.length}`),t.includes("root-oh-package")){l.info("[DependencyMapWatcher] Root oh-package.json5 in batch \u2192 full reload"),this.emit("reload",{fullReload:!0,kinds:["projectDepsChanged"]});return}let i=new Set,o=new Set,s=new Set,a=[];this.processTagsIntoSets(t,i,o,s),this.processRenameEntries(n,i,o,s,a);for(let d of o)s.delete(d);if(o.size===0&&s.size===0&&a.length===0){l.info("[DependencyMapWatcher] Coalesced batch has no effective changes, skipping");return}let c=this.buildAddedNamesSet(t,n);this.emitIncrementalReload(i,o,s,c,a)}normalizeSrcPath(t){return F(t).replace(/^\.\//,"").replace(/\/$/,"")}buildModuleLookupMaps(t){let n=new Map(t.map(o=>[o.name,o])),i=new Map(t.map(o=>[this.normalizeSrcPath(o.srcPath),o]));return{byName:n,bySrcPath:i}}detectModuleRenames(t,n,i,o){for(let[s,a]of t){let c=n.get(s);if(!c||c.name===a.name)continue;this.pendingRenames.push({kind:"moduleRenamed",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleRenamed"}}),i.add(a.name),o.add(c.name);let d=Q.join(this.depMapDir,a.name,I.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(d)),l.info(`[DependencyMapWatcher] Module renamed: ${a.name} \u2192 ${c.name} (srcPath=${s})`)}}detectModuleMoves(t,n,i,o){for(let[s,a]of t){if(i.has(s))continue;let c=n.get(s);!c||c.srcPath===a.srcPath||(this.pendingRenames.push({kind:"moduleMoved",info:{oldName:a.name,newName:c.name,oldSrcPath:a.srcPath,newSrcPath:c.srcPath,kind:"moduleMoved"}}),i.add(s),o.add(s),l.info(`[DependencyMapWatcher] Module moved: ${s} srcPath ${a.srcPath} \u2192 ${c.srcPath}`))}}detectAddedModules(t,n,i){for(let[o]of t)i.has(o)||n.has(o)||(this.pendingTags.push(`dep-added:${o}`),i.add(o))}detectRemovedModules(t,n,i){for(let[o]of t)if(!i.has(o)&&!n.has(o)){this.pendingTags.push(`dep-removed:${o}`),i.add(o);let s=Q.join(this.depMapDir,o,I.OH_PACKAGE_JSON5);this.contentHashes.delete(this.canonicalPath(s))}}logDepMapDiffResult(){let t=this.pendingTags.filter(i=>i.startsWith("dep-")),n=this.pendingRenames.map(i=>`${i.kind}(${i.info.oldName}\u2192${i.info.newName})`);l.info(`[DependencyMapWatcher] dependencyMap.json5 diff complete, depTags: [${t.join(", ")}], renames: [${n.join(", ")}]`)}applyDepMapJsonDiff(){let t=this.parseModulesFromDepMap(),{byName:n,bySrcPath:i}=this.buildModuleLookupMaps(this.lastModules),{byName:o,bySrcPath:s}=this.buildModuleLookupMaps(t),a=new Set,c=new Set;this.detectModuleRenames(i,s,a,c),this.detectModuleMoves(n,o,a,c),this.detectAddedModules(o,n,c),this.detectRemovedModules(n,o,a),this.lastModules=t,this.logDepMapDiffResult()}computeFileHash(t){try{let n=Ie.readFileSync(t,"utf-8");return Ud("sha256").update(n).digest("hex")}catch{return null}}};import{spawn as zd}from"child_process";import*as _n from"path";import*as $n from"fs";var Vd=600*1e3;function qd(r,e,t){let n=t.split(/\s+/).filter(i=>i.length>0);return[r,[e,...n]]}function Yd(r){let e="",t="";return r.stdout?.on("data",n=>{e+=n.toString()}),r.stderr?.on("data",n=>{t+=n.toString()}),{stdout:e,stderr:t}}function Gd(r,e,t){if(e)return{success:!1,output:"Build process killed by signal "+e+`.
|
|
1236
1236
|
Output so far:
|
|
1237
1237
|
`+t,exitCode:-1};let n=r??-1;return{success:n===0,output:t,exitCode:n}}function Jd(r,e,t){return new Promise(n=>{let i=zd(r[0],r[1],{cwd:e,env:t,windowsHide:!0,stdio:["ignore","pipe","pipe"]}),{stdout:o,stderr:s}=Yd(i),a=setTimeout(()=>{i.kill();let c=[o,s].filter(Boolean).join(`
|
|
1238
1238
|
`).trim();n({success:!1,output:`Build process timeout after 10 minutes.
|
|
@@ -1241,24 +1241,24 @@ Output so far:
|
|
|
1241
1241
|
`).trim()||"";n(Gd(c,d,u))}),i.on("error",c=>{clearTimeout(a),n({success:!1,output:`Build execution exception: ${c.message}`,exitCode:-1})})})}async function Vr(r,e,t,n,i){let o={...process.env,DEVECO_SDK_HOME:n},s=qd(e,t,i);return Jd(s,r,o)}function Kd(r){let e=_n.join(_n.dirname(r),"tools","hvigor","bin","hvigorw.js");return{node_path:rn(r),hvigor_path:e,sdk_path:r}}function Xd(r){return!r.node_path||!$n.existsSync(r.node_path)?`Node path not found or invalid: ${r.node_path}`:!r.hvigor_path||!$n.existsSync(r.hvigor_path)?`Hvigor path not found or invalid: ${r.hvigor_path}`:!r.sdk_path||!$n.existsSync(r.sdk_path)?`SDK path not found or invalid: ${r.sdk_path}`:null}var Zd="--sync -p product=default --analyze=normal --parallel --incremental --no-daemon";async function Rs(r,e){try{let t=Kd(e),n=Xd(t);return n!=null?(l.info(`Config validation failed: ${n}`),!1):(await Vr(r,t.node_path,t.hvigor_path,e,Zd)).success}catch(t){return l.info(`syncProject failed: ${JSON.stringify(t)}`),!1}}import{spawn as Qd}from"child_process";import*as qr from"fs";import*as Mt from"path";var eu=["install","--all"];function tu(r){let e=r.replace(/sdk\/?$/i,"tools"),t=Mt.join(e,"ohpm","bin","pm-cli.js");if(qr.existsSync(t))return t;let n=r.toLowerCase().endsWith("sdk")?Mt.dirname(r):r;return t=Mt.join(n,"ohpm","bin","pm-cli.js"),qr.existsSync(t)?t:null}async function nu(r,e,t,n){return new Promise(i=>{let o=Qd(r,[e,...eu],{cwd:t,env:{...process.env,DEVECO_SDK_HOME:n},windowsHide:!0,stdio:["ignore","pipe","pipe"]}),s="",a="";o.stdout?.on("data",c=>{s+=c.toString()}),o.stderr?.on("data",c=>{a+=c.toString()}),o.on("close",c=>{let d=[s,a].filter(Boolean).join(`
|
|
1242
1242
|
`);i({exitCode:c??-1,output:d})}),o.on("error",c=>{let d=[s,a].filter(Boolean).join(`
|
|
1243
1243
|
`);i({exitCode:-1,output:d+`
|
|
1244
|
-
`+c.message})})})}function ru(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}async function Os(r,e){try{let t=rn(e);if(!t)return l.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let n=tu(e);if(!n)return l.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await nu(t,n,r,e);return ru(o),i===0?(l.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(l.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),l.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return l.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Ns={UNINITIALIZED:-32099,UNKNOWN:-32e3},xt=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,Ns.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,Ns.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var st=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t){if(l.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return l.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),!1;if(!await Os(e,t))return l.error("[ArktsLspManager] ohpm install failed"),!1;let i=await Rs(e,t);return i?l.info("[ArktsLspManager] syncProject completed successfully"):l.error("[ArktsLspManager] syncProject failed"),i}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){l.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Hn(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)l.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:M,method:g.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?xt.uninitialized(t):xt.unknown();this.onMessage({jsonrpc:M,method:g.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(l.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:M,method:g.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new jn(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Fn(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){l.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:M,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:n}}),this.onMessage({jsonrpc:M,method:g.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}handleConfigChanged(e){l.info(`[ArktsLspManager] Config file changed: ${e.filePath}`);try{let t=e.kind??4,n={jsonrpc:M,method:g.WORKSPACE_DID_CHANGE_CONFIGURATION,params:{relativePath:e.relativePath,timestamp:e.timestamp,changeSource:e.source,changeSignal:t,...e.filePath&&{filePath:e.filePath},...e.fileName!==void 0&&{fileName:e.fileName},...e.moduleName!==void 0&&{moduleName:e.moduleName},...e.removedModuleName!==void 0&&{removedModuleName:e.removedModuleName}}};this.onMessage(n)}catch(t){l.error(`[ArktsLspManager] Failed to handle config change: ${t instanceof Error?t.message:String(t)}`)}}};var iu=120*1e3,ou=300*1e3,su=180*1e3,au=10080*60*1e3,cu=7200*60*1e3,at=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;arktsLangServerPath;nodeMaxOldSpaceSize;constructor(e,t,n){this.projectPath=e,this.devecoPath=t??"",this.arktsLangServerPath=null,this.nodeMaxOldSpaceSize=n}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:Yr.object({files:Yr.array(Yr.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:n}=this.resolveProjectAndDeveco(),i=ae(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Fr(s,au,"[ArkTS-Check]"),Fr(o,cu,"[ArkTS-Check]")}),bs(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a,d=ee.join(se(t),"sdk");
|
|
1244
|
+
`+c.message})})})}function ru(r){r.split(/\r?\n/).filter(Boolean).forEach(e=>l.info("[ohpm] %s",e))}async function Os(r,e){try{let t=rn(e);if(!t)return l.error("node \u8DEF\u5F84\u4E0D\u5B58\u5728"),!1;let n=tu(e);if(!n)return l.error("ohpm (pm-cli.js) \u4E0D\u5B58\u5728"),!1;let{exitCode:i,output:o}=await nu(t,n,r,e);return ru(o),i===0?(l.info("ohpm \u5B89\u88C5\u6210\u529F"),!0):(l.error("ohpm \u5B89\u88C5\u5931\u8D25\uFF0C\u9000\u51FA\u7801: %s",i),l.error("ohpm \u8F93\u51FA: %s",o),!1)}catch(t){return l.error("ohpm \u5B89\u88C5\u5F02\u5E38",t),!1}}var Ns={UNINITIALIZED:-32099,UNKNOWN:-32e3},xt=class r extends Error{code;constructor(e,t){super(e),this.name="ArkTsProxyError",this.code=t}static uninitialized(e){return new r(e,Ns.UNINITIALIZED)}static unknown(e="Unknown error"){return new r(e,Ns.UNKNOWN)}toJsonRpcErrorParams(){return{code:this.code,message:this.message}}};var st=class{config;lspProxy=null;configWatcher=null;depMapWatcher=null;isInitialized=!1;lastEditorOpenFiles=[];onMessage=()=>{};disposeOnce=null;constructor(e){this.config=e}setOnMessage(e){this.onMessage=e}async start(e=[]){this.lastEditorOpenFiles=e,this.startConfigWatcher(),this.startLspProxy(e)}sendNotification(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendNotification before LSP ready, dropped");return}this.lspProxy.sendNotification(e)}sendRequest(e){if(!this.lspProxy){l.warn("[ArktsLspManager] sendRequest before LSP ready, dropped");return}this.lspProxy.sendRequest(e)}static async handleSyncProject(e,t){if(l.info("[ArktsLspManager] Received arkts/syncProject"),!e||!t)return l.error("[ArktsLspManager] handleSyncProject: workspaceRoot or sdkPath is empty"),!1;if(!await Os(e,t))return l.error("[ArktsLspManager] ohpm install failed"),!1;let i=await Rs(e,t);return i?l.info("[ArktsLspManager] syncProject completed successfully"):l.error("[ArktsLspManager] syncProject failed"),i}async dispose(){return this.disposeOnce||(this.disposeOnce=this.performDispose()),this.disposeOnce}async performDispose(){try{this.configWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] configWatcher stop error: ${e}`)}try{this.depMapWatcher?.stop()}catch(e){l.warn(`[ArktsLspManager] depMapWatcher stop error: ${e}`)}if(this.configWatcher=null,this.depMapWatcher=null,this.lspProxy){try{await this.lspProxy.dispose()}catch(e){l.warn(`[ArktsLspManager] lspProxy dispose error: ${e}`)}this.lspProxy=null}this.isInitialized=!1}startLspProxy(e){let t=new Hn(this.config.sdkPath,this.config.arktsLangServerPath,this.config.workspaceRoot,this.config.indexLogPath,this.config.nodeMaxOldSpaceSize);t.setOnMessage(n=>this.handleLspMessage(n)),t.start(e,n=>this.handleLspInitialized(n)),this.lspProxy=t}handleLspInitialized=e=>{if(this.isInitialized=e,e)l.info("[ArktsLspManager] LSP initialized"),this.startDependencyMapWatcher(),this.onMessage({jsonrpc:M,method:g.ARKTS_INITIALIZED,params:{}});else{let t=this.lspProxy?.consumeStartErrorMessage();l.error(`[ArktsLspManager] LSP initialization failed: ${t}`);let n=t?xt.uninitialized(t):xt.unknown();this.onMessage({jsonrpc:M,method:g.ARKTS_INITIALIZATION_FAILED,params:n.toJsonRpcErrorParams()}),this.lspProxy=null}};handleLspMessage(e){this.onMessage(e)}maybeRetryLspAfterSuccessfulSync(){this.isInitialized||this.lspProxy!==null||(l.info("[ArktsLspManager] Retrying LSP startup after successful sync"),this.onMessage({jsonrpc:M,method:g.ARKTS_REINITIALIZING,params:{}}),this.startLspProxy(this.lastEditorOpenFiles))}startConfigWatcher(){this.configWatcher||(this.configWatcher=new jn(this.config.workspaceRoot),this.configWatcher.on("configChanged",e=>this.handleConfigChanged(e)),this.configWatcher.start())}startDependencyMapWatcher(){this.depMapWatcher||(this.depMapWatcher=new Fn(this.config.workspaceRoot),this.depMapWatcher.on("reload",e=>{if(!this.lspProxy){l.warn("[ArktsLspManager] LspServerProxy not initialized, skip reload");return}let n=this.lspProxy.reloadDependenciesOnly(e).map(i=>({modulePath:i.modulePath??"",dependencies:i.dependencies??{},dynamicDependencies:i.dynamicDependencies??{}}));this.lspProxy.sendNotification({jsonrpc:M,method:g.ON_DID_CHANGE_PACKAGE_DEPENDENCIES_CLIENT,params:{moduleSet:n}}),this.onMessage({jsonrpc:M,method:g.ARKTS_SYNC_COMPLETED,params:{success:!0}})}),this.depMapWatcher.start())}handleConfigChanged(e){l.info(`[ArktsLspManager] Config file changed: ${e.filePath}`);try{let t=e.kind??4,n={jsonrpc:M,method:g.WORKSPACE_DID_CHANGE_CONFIGURATION,params:{relativePath:e.relativePath,timestamp:e.timestamp,changeSource:e.source,changeSignal:t,...e.filePath&&{filePath:e.filePath},...e.fileName!==void 0&&{fileName:e.fileName},...e.moduleName!==void 0&&{moduleName:e.moduleName},...e.removedModuleName!==void 0&&{removedModuleName:e.removedModuleName}}};this.onMessage(n)}catch(t){l.error(`[ArktsLspManager] Failed to handle config change: ${t instanceof Error?t.message:String(t)}`)}}};var iu=120*1e3,ou=300*1e3,su=180*1e3,au=10080*60*1e3,cu=7200*60*1e3,at=class{manager=null;diagnosticWaiters=new Map;initialized=!1;initializing=!1;initPromise=null;initDeadlineTimer=null;initResolve=null;initReject=null;projectPath;devecoPath;arktsLangServerPath;nodeMaxOldSpaceSize;constructor(e,t,n){this.projectPath=e,this.devecoPath=t??"",this.arktsLangServerPath=null,this.nodeMaxOldSpaceSize=n}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:Yr.object({files:Yr.array(Yr.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:n}=this.resolveProjectAndDeveco(),i=ae(e),{logPath:o,indexPath:s}=this.getLogAndIndexPath(i);setImmediate(()=>{Fr(s,au,"[ArkTS-Check]"),Fr(o,cu,"[ArkTS-Check]")}),bs(o);let a=this.nodeMaxOldSpaceSize?parseInt(this.nodeMaxOldSpaceSize,10):NaN,c=Number.isNaN(a)?void 0:a,d=ee.join(se(t),"sdk");m.info(`ArktsCheck devecoPath: ${t}, contentRoot: ${se(t)}, sdkPath: ${d}`),this.manager=new st({sdkPath:d,arktsLangServerPath:n,workspaceRoot:F(i),indexLogPath:s,nodeMaxOldSpaceSize:c}),this.manager.setOnMessage(u=>this.handleLspMessage(u)),await new Promise((u,b)=>{this.initResolve=u,this.initReject=b,this.armInitTimer(ou),this.manager.start([]).catch(k=>{let ce=k instanceof Error?k:new Error(String(k));this.failInit(ce)})})}resolveProjectAndDeveco(){let e=pe(this.projectPath);if(!e)throw new Error(`Failed to find Harmony project from path: ${this.projectPath}`);this.projectPath=e;let t=this.devecoPath??Re();if(m.debug(`DevEco Studio installation path: ${t}, this.devecoPath: ${this.devecoPath}`),!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=ss(t);if(!n)throw new Error("arkts-lang-server path not found");return this.arktsLangServerPath=n,{harmonyRoot:e,devecoPath:t,arktsLangServerPath:n}}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=Et(Oe(e)),n=jr(e),i=await ge.promises.readFile(e,"utf8"),s=`deveco.apptool.${ee.extname(e).replace(/^\./,"")||"plaintext"}`,a=new Promise((d,u)=>{let b=setTimeout(()=>{this.diagnosticWaiters.delete(t)&&u(new Error("Wait for diagnostics timeout"))},iu);this.diagnosticWaiters.set(t,{resolve:d,reject:u,timer:b})}),c={textDocument:{uri:n,text:i,languageId:s,version:i.length},editorFiles:[n],isFromEditor:!1};m.debug(`textDocument/didOpen uri=${n} content_len=${i.length}`),this.sendNotification("textDocument/didOpen",c);try{return await a}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:n},isManual:!1})}}async handleCall(e){if(!this.initialized)return this.buildNotReadyResponse();let t=[],n=[],i=this.collectValidFiles(e.files,t);return i.length===0?{content:[{type:"text",text:t.length>0?t.join(`
|
|
1245
1245
|
`):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(i,t,n),this.formatCallResult(t,n))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=ee.isAbsolute(o)?o:ee.join(n,o);if(!ge.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!ge.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${o}`);continue}i.push(s)}return i}async runDiagnosticsForFiles(e,t,n){for(let i of e){await ls(500);try{let o=await this.checkFile(i);n.push(lu(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let n=[];e.length>0&&n.push(e.join(`
|
|
1246
1246
|
`)),t.length>0&&n.push(t.join(`
|
|
1247
1247
|
`));let i=n.join(`
|
|
1248
|
-
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){
|
|
1248
|
+
`).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){m.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,n=t.method;if(n)switch(n){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(su),m.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{m.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";m.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let n=this.resolveDiagnosticWaiter(t);if(!n)return;if(typeof e.errorMessage=="string"){m.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),n.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;m.debug(`diagnostics received uri=${t} count=${o}`),n.resolve(Array.isArray(i)?i:[])}resolveDiagnosticWaiter(e){let t=Et(e),n=this.popDiagnosticWaiter(t);if(n)return n;for(let i of us(e)){let o=this.popDiagnosticWaiter(i);if(o)return o}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,n]of this.diagnosticWaiters)clearTimeout(n.timer),n.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=ee.join(nn(),"ArkTSCheck"),n=ee.join(t,"mapping-config.properties"),i=ps(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=ee.join(t,"lsp-log",String(i),o),a=ee.join(t,"lsp-index",String(i));return ge.mkdirSync(s,{recursive:!0}),ge.mkdirSync(a,{recursive:!0}),{logPath:ae(s),indexPath:ae(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function lu(r,e){if(Array.isArray(e))return e.length===0?`${r} => no diagnostics`:`${r} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${r} diagnostic failed, error_message: ${t}`}return`${r} => diagnostic failed, result: ${JSON.stringify(e)}`}import{spawn as du}from"child_process";import*as A from"fs";import*as O from"path";import{z as Gr}from"zod";var Ls=60*1e3,uu=30*1e3,pu=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),hu=1e3,Jr=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{m.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let n=ae(this.projectPath),i=Oe(n),o=O.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.6.1"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,Ls),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,m.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=Ls,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(n=>setTimeout(n,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=A.realpathSync(e)}catch{t=e}let n=Oe(t),i=ds(t),o=await A.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let d=setTimeout(()=>{this.diagnosticWaiters.delete(n)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},uu);this.diagnosticWaiters.set(n,{resolve:a,reject:c,timer:d})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:n,languageId:i,version:1,text:o}})}catch(a){let c=this.diagnosticWaiters.get(n);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(n)),a}try{return await s}finally{await this.closeFile(n).catch(a=>{m.warn(`[CppCheck] didClose failed for ${n}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){m.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){m.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){m.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let n={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(n);return}pu.has(e)&&this.queuedDocumentNotifications.push(n)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,n){let i=this.nextRequestId++;return new Promise((o,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(i)&&s(new Error(`Timed out waiting for ${e} response`))},n);this.pendingRequests.set(i,{resolve:o,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:i,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(i)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,n)=>{let i;try{i=JSON.stringify(e)}catch(u){n(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
|
|
1249
1249
|
\r
|
|
1250
1250
|
`,"ascii"),a=!1,c=u=>{a||(a=!0,u?n(u):t())};if(this.clangdStdin.write(Buffer.concat([s,o]),u=>{u?c(u):a||c()}))c();else{let u=()=>c();this.clangdStdin.once("drain",u)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
|
|
1251
1251
|
\r
|
|
1252
|
-
`);if(t<0)return;let n=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(n);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){
|
|
1252
|
+
`);if(t<0)return;let n=this.clangdBuffer.slice(0,t).toString("ascii"),i=/content-length:\s*(\d+)/i.exec(n);if(!i){this.clangdBuffer=this.clangdBuffer.slice(t+4);continue}let o=parseInt(i[1],10),s=t+4+o;if(this.clangdBuffer.length<s)return;let a=this.clangdBuffer.slice(t+4,s).toString("utf8");this.clangdBuffer=this.clangdBuffer.slice(s);try{let c=JSON.parse(a);this.dispatchMessage(c)}catch(c){m.error(`[CppCheck] Failed to parse C++ LSP JSON message: ${c}`)}}}dispatchMessage(e){if(typeof e.id=="number"){let t=this.pendingRequests.get(e.id);t&&(this.pendingRequests.delete(e.id),clearTimeout(t.timer),e.error?t.reject(new Error(e.error.message??JSON.stringify(e.error))):t.resolve(e.result??null));return}if(e.method==="textDocument/publishDiagnostics"&&e.params){let t=e.params,n=t.uri;if(!n)return;let i=mu(n),o=this.diagnosticWaiters.get(i);if(o){this.diagnosticWaiters.delete(i),clearTimeout(o.timer);let s=Array.isArray(t.diagnostics)?t.diagnostics:[];m.info(`[CppCheck] Received C++ diagnostics for ${i} (${s.length} entries)`),o.resolve(s)}}}failAll(e){for(let[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(e);this.pendingRequests.clear();for(let[,t]of this.diagnosticWaiters)clearTimeout(t.timer),t.reject(e);this.diagnosticWaiters.clear()}async acquireFileCheckLock(){let e=this.fileCheckLock,t;return this.fileCheckLock=new Promise(n=>{t=n}),await e,t}};function mu(r){try{let e=new URL(r);if(e.protocol==="file:"){let t=decodeURIComponent(e.pathname);return process.platform==="win32"&&/^\/[a-zA-Z]:/.test(t)&&(t=t.slice(1)),Oe(t)}}catch{}return r}function fu(r){let e=O.extname(r).replace(/^\./,"").toLowerCase();return["c","cpp","cxx","cc","h","hpp","hxx","hh","c++","h++"].includes(e)}function gu(r,e){let t=O.join(r,e.name);return e.isDirectory()?e.name===".cxx"||Hs(t):fu(t)}function Hs(r){if(!A.existsSync(r))return!1;try{return A.readdirSync(r,{withFileTypes:!0}).some(t=>gu(r,t))}catch{}return!1}function js(r){let t=new He(r).getAllModuleInfo(),n=[];for(let i of t){let o=i.srcPath.replace(/^\.\//,""),s=O.join(r,o);Hs(s)&&n.push(i)}return n}function yu(r){let e=[],n=new He(r).getAllModuleInfo();for(let i of n){let o=i.srcPath.replace(/^\.\//,""),s=O.join(r,o,".cxx");A.existsSync(s)&&Fs(s,e)}return e}function Fs(r,e){try{let t=A.readdirSync(r,{withFileTypes:!0});for(let n of t){let i=O.join(r,n.name);n.isDirectory()?Fs(i,e):n.name==="compile_commands.json"&&e.push(i)}}catch{}}function vu(r){let e=[];for(let t of r)try{let n=A.readFileSync(t,"utf8"),i=JSON.parse(n);e.push(...i)}catch{}return e}function wu(r,e){let t=O.join(r,...Lr.slice(0,-1));A.mkdirSync(t,{recursive:!0});let n=O.join(t,"compile_commands.json");A.writeFileSync(n,JSON.stringify(e,null,2),"utf8")}function bu(r){let e=yu(r);if(e.length>0){let t=vu(e);wu(r,t),m.info(`[CppCheck] compile_commands.json \u5DF2\u751F\u6210\uFF0C\u5171 ${t.length} \u6761\u7F16\u8BD1\u547D\u4EE4`)}else m.warn("[CppCheck] \u672A\u627E\u5230\u4EFB\u4F55 compile_commands.json \u6587\u4EF6")}function Su(r){let e=new Set;for(let t of r)if(t.file)try{e.add(A.realpathSync(t.file))}catch{e.add(t.file)}return e}function Pu(r,e){try{let t=A.realpathSync(r);if(!e.has(t))return m.info(`[CppCheck] File not covered by compile_commands.json: ${r}`),!1}catch{}return!0}function Eu(r,e){if(!A.existsSync(r))return!1;try{let t=A.readFileSync(r,"utf8"),n=JSON.parse(t),i=Su(n);for(let o of e)if(!Pu(o,i))return!1;return!0}catch(t){return m.warn(`[CppCheck] Failed to read/parse compile_commands.json: ${t}`),!1}}function Du(r,e,t){let n=O.join(se(e),"sdk"),i=process.platform==="win32"?"Windows":process.platform==="darwin"?"Mac":"Linux",o=process.execPath||"node",s=O.join(se(e),"tools");m.info(`CppCheck devecoPath: ${e}, contentRoot: ${se(e)}, sdkPath: ${n}, toolsDir: ${s}`);let a=process.platform==="win32"?O.join(s,"hvigor","bin","hvigorw.bat"):O.join(s,"hvigor","bin","hvigorw.js");for(let c of t){let d=["--mode","module","-p",`module=${c.name}`,"-p","product=default","compileNative","--analyze=normal","--parallel","--incremental","--no-daemon"].join(" ");m.info(`[CppCheck] Running compileNative for module: ${c.name}`);let u=Vr(r,o,a,n,d,i);u.success?m.info(`[CppCheck] compileNative ${c.name} \u6210\u529F`):m.warn(`[CppCheck] compileNative ${c.name} \u5931\u8D25: ${u.output}`)}}function Iu(r,e){let t=js(r);if(t.length===0){m.info("[CppCheck] \u672A\u53D1\u73B0\u542BC++\u7684\u6A21\u5757\uFF0C\u8DF3\u8FC7\u521D\u59CB\u5316");return}m.info(`[CppCheck] \u53D1\u73B0 ${t.length} \u4E2A\u542BC++\u7684\u6A21\u5757: ${t.map(n=>n.name).join(", ")}`),Du(r,e,t),bu(r)}var ct=class{projectPath;devecoPath;clangdProcess=null;client=null;initializedProjectPath=null;initializing=!1;initPromise=null;pollHandle=null;backendReady=!1;constructor(e,t){this.projectPath=e,this.devecoPath=en(t??"")??t??null}static getToolDefinition(){return{name:"check_cpp_files",description:"\u5BF9\u4F20\u5165\u7684 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE clangd \u8BCA\u65AD\u4FE1\u606F\u3002",inputSchema:Gr.object({files:Gr.array(Gr.string()).describe('\u5F85\u68C0\u67E5\u7684 C/C++ \u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u683C\u5F0F\u4E3A ["file1.cpp","file2.hpp",...]')})}}isInitializing(){return this.initializing}isInitialized(){return this.client!==null&&this.initializedProjectPath!==null}async handleCall(e){let t=[],n=[],i=this.collectValidFiles(e.files,t);if(i.length===0)return{content:[{type:"text",text:t.length>0?t.join(`
|
|
1253
1253
|
`):"\u6CA1\u6709\u6709\u6548\u7684 C/C++ \u6587\u4EF6"}],isError:!0};let o;try{o=await this.ensureInitializedWithFiles(i)}catch(a){return t.push(a.message),{content:[{type:"text",text:t.join(`
|
|
1254
|
-
`)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,n)&&this.shutdown().catch(a=>{
|
|
1254
|
+
`)}],isError:!0}}return await this.runDiagnosticsForFiles(o,i,t,n)&&this.shutdown().catch(a=>{m.warn(`[CppCheck] shutdown after diagnostic failure: ${a}`)}),this.formatCallResult(t,n)}async runDiagnosticsForFiles(e,t,n,i){let o=!1;for(let s of t)try{let a=await e.checkFile(s);a.length===0?i.push(`${s} => \u65E0\u8BCA\u65AD`):i.push(`${s} => Diagnostic: ${JSON.stringify(a)}`)}catch(a){o=!0,n.push(`${s} => \u83B7\u53D6\u8BCA\u65AD\u5931\u8D25: ${a.message}`)}return o}formatCallResult(e,t){let n=e.length>0;return!n&&t.length===0&&t.push("\u6CA1\u6709\u8FD4\u56DE\u4EFB\u4F55\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:[t.join(`
|
|
1255
1255
|
`),e.join(`
|
|
1256
1256
|
`)].filter(o=>o.trim().length>0).join(`
|
|
1257
|
-
`).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=ae(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(
|
|
1258
|
-
`)}],isError:!0}:null}let n=e.filter(i=>lt.isAbsolute(i));return n.length>0?(
|
|
1259
|
-
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(b=>typeof b=="string"):[];if(t.length===0)return
|
|
1257
|
+
`).trim()}],isError:n}}async ensureInitializedWithFiles(e){let t=ae(this.projectPath);if(this.prepareCppCheck(t,e)){this.client&&this.initializedProjectPath&&(m.info("[CppCheck] Re-initializing C++ project due to file changes"),await this.shutdown());let i=this.devecoPath??Re();if(!i)throw new Error("DevEco Studio installation path not found");this.devecoPath=i,Iu(t,i)}else if(this.client&&this.initializedProjectPath){let i=ae(this.projectPath);if(this.initializedProjectPath===i)return this.client;await this.shutdown()}return this.doEnsureInitialized()}prepareCppCheck(e,t){let n=Qt(e);return A.existsSync(n)?js(e).length===0?(m.info("[CppCheck] No cpp modules found, no initialization needed"),!1):Eu(n,t)?(m.info("[CppCheck] All files covered, no initialization needed"),!1):(m.info("[CppCheck] Files not fully covered by compile_commands.json, needs initialization"),!0):(m.info("[CppCheck] compile_commands.json not found, needs initialization"),!0)}async doEnsureInitialized(){if(this.initPromise&&(await this.initPromise,this.client))return this.client;if(this.initializing=!0,this.initPromise=this.doInitialize().finally(()=>{this.initializing=!1,this.initPromise=null}),await this.initPromise,!this.client)throw new Error("C++ LSP failed to initialize");return this.client}async doInitialize(){let e=this.resolveProjectRoot();this.client=new Jr,await this.client.initialize(e),this.initializedProjectPath=e,m.info(`[CppCheck] Client initialized in wrapper mode for workspace: ${e}`),this.startPollingForClangd(e)}resolveProjectRoot(){let e=pe(this.projectPath);if(!e)throw new Error(`Failed to find Harmony project from path: ${this.projectPath}`);return this.projectPath=e,ae(e)}startPollingForClangd(e){let t=Qt(e);if(A.existsSync(t)){m.info("[CppCheck] compile_commands.json found, spawning clangd immediately"),this.spawnAndConnectClangd(e).catch(n=>{m.error(`[CppCheck] Immediate clangd spawn failed: ${n}`)});return}m.info("[CppCheck] compile_commands.json not found, starting poll..."),this.pollHandle=setInterval(()=>{if(!this.client||this.client.isClosed()||this.backendReady){this.stopPolling();return}A.existsSync(t)&&(this.stopPolling(),m.info("[CppCheck] compile_commands.json found via poll, spawning clangd..."),this.spawnAndConnectClangd(e).catch(n=>{m.error(`[CppCheck] Clangd spawn from poll failed: ${n}`)}))},hu)}stopPolling(){this.pollHandle&&(clearInterval(this.pollHandle),this.pollHandle=null)}async spawnAndConnectClangd(e){let{clangdPath:t,compileCommandsDir:n}=this.resolveClangdPaths(e);m.info(`[CppCheck] Starting clangd for workspace: ${e} (clangd=${t})`);let i=this.spawnClangd(t,e,n);this.clangdProcess=i;try{await this.client.connectClangdProcess(i.stdin,i.stdout),this.backendReady=!0,m.info(`[CppCheck] clangd connected for workspace: ${e}`)}catch(o){if(m.error(`[CppCheck] Failed to connect clangd: ${o}`),this.clangdProcess&&!this.clangdProcess.killed){try{this.clangdProcess.kill()}catch{}this.clangdProcess=null}throw o}}resolveClangdPaths(e){let t=this.devecoPath??Re();if(!t)throw new Error("DevEco Studio installation path not found");this.devecoPath=t;let n=as(t);if(!n)throw new Error("clangd executable not found inside DevEco Studio SDK");let i=Qt(e),o=O.dirname(i);return{clangdPath:n,compileCommandsDir:o}}spawnClangd(e,t,n){let i=du(e,[`--compile-commands-dir=${n}`],{cwd:t,stdio:["pipe","pipe","pipe"]});if(!i.stdin||!i.stdout||!i.stderr)throw new Error("Failed to start clangd: stdio not available");return i.stderr.on("data",o=>{let s=o.toString("utf8").trimEnd();s&&m.warn(`[CppLsp stderr] ${s}`)}),i.on("exit",(o,s)=>{m.warn(`[CppCheck] clangd exited code=${o} signal=${s??"null"}`),this.clangdProcess===i&&(this.clangdProcess=null,this.backendReady=!1)}),i.on("error",o=>{m.error(`[CppCheck] clangd spawn error: ${o}`)}),i}collectValidFiles(e,t){let n=this.projectPath,i=[];for(let o of e){let s=O.isAbsolute(o)?o:O.join(n,o);if(!A.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!A.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${o}`);continue}if(!tn(s)){t.push(`\u4E0D\u662F\u53D7\u652F\u6301\u7684 C/C++ \u6587\u4EF6: ${o}`);continue}try{i.push(A.realpathSync(s))}catch{i.push(s)}}return i}async shutdown(){this.stopPolling();let e=this.client,t=this.clangdProcess;if(this.client=null,this.clangdProcess=null,this.initializedProjectPath=null,this.backendReady=!1,e)try{await e.close()}catch(n){m.warn(`[CppCheck] client.close() failed: ${n}`)}if(t&&!t.killed)try{t.kill()}catch(n){m.warn(`[CppCheck] failed to kill clangd: ${n}`)}}};var $s=(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))($s||{}),Xr=3,Wn=class{server;toolRouter;config={};arktsCheckTool=null;cppCheckTool=null;projectState=0;workspaceRoot="";sdkPath="";initPromise=null;needsReinit=!1;initRetryCount=0;originalProjectPath="";constructor(e={}){this.config=e,_r(e.debug??!1);let t,n=e.projectPath?.trim()??"";this.originalProjectPath=n,n==="."?(t=process.cwd(),m.info(`Constructor: configuredPath is '.', startPath: '${t}'`)):n===""?(t="",m.info("Constructor: configuredPath is empty, startPath remains empty")):(t=n,m.info(`Constructor: using configured path as startPath: '${t}'`));let i=pe(t);m.info(`Constructor: findHarmonyProject('${t}') => ${i??"null"}`),this.config.projectPath=i??void 0,this.server=new Cu({name:"devecocli-mcp-server",version:"0.0.1"}),this.toolRouter=Rr(),this.registerTools()}registerTools(){this.toolRouter.add({name:"check",description:"\u5BF9\u4F20\u5165\u7684 ArkTS (.ets) \u6216 C/C++ \u6587\u4EF6\u8FDB\u884C\u9759\u6001\u8BED\u6CD5\u68C0\u67E5\u5E76\u8FD4\u56DE\u8BCA\u65AD\u4FE1\u606F\u3002\u5DE5\u5177\u4F1A\u6839\u636E\u6587\u4EF6\u6269\u5C55\u540D\u81EA\u52A8\u9009\u62E9\u68C0\u67E5\u5668\uFF1A.ets \u8D70 ArkTS-Check\uFF0C.c/.cc/.cpp/.cxx/.h/.hh/.hpp/.hxx \u7B49\u8D70 clangd\u3002",inputSchema:Kr.object({files:Kr.array(Kr.string()).describe('\u5F85\u68C0\u67E5\u7684\u6587\u4EF6\u8DEF\u5F84\u5217\u8868\uFF0C\u53EF\u540C\u65F6\u5305\u542B ArkTS (.ets) \u548C C/C++ \u6587\u4EF6\uFF0C\u683C\u5F0F\u4E3A ["src/main.ets","native/foo.cpp",...]')})},async e=>this.handleCheckCall(e))}validateContainment(e){let t=this.config.projectPath;if(t){let i=[];for(let o of e){let s=E.isPathContainedWithSymlink(o,t);s.contained||(m.warn(`Containment check failed: ${s.reason}`),i.push(s.reason))}return i.length>0?{content:[{type:"text",text:i.join(`
|
|
1258
|
+
`)}],isError:!0}:null}let n=e.filter(i=>lt.isAbsolute(i));return n.length>0?(m.warn(`Absolute paths rejected (no project root): ${n.join(", ")}`),{content:[{type:"text",text:n.map(i=>`\u4E0D\u5141\u8BB8\u4F7F\u7528\u7EDD\u5BF9\u8DEF\u5F84: ${i}`).join(`
|
|
1259
|
+
`)}],isError:!0}):null}async handleCheckCall(e){let t=Array.isArray(e.files)?e.files.filter(b=>typeof b=="string"):[];if(t.length===0)return m.warn("check tool called with empty files list"),{content:[{type:"text",text:"\u6CA1\u6709\u4F20\u5165\u4EFB\u4F55\u6587\u4EF6"}],isError:!0};let n=this.validateContainment(t);if(n)return n;let{etsFiles:i,cppFiles:o,unsupported:s}=ku(t);s.length>0&&m.warn(`Unsupported file types in check request: ${s.join(", ")}`);let a=s.map(b=>`\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B: ${b}\uFF08\u4EC5\u652F\u6301 .ets \u4E0E C/C++ \u6E90/\u5934\u6587\u4EF6\uFF09`),c=[];i.length>0&&this.mergeCheckResult(await this.callArktsCheck(i),a,c),o.length>0&&this.mergeCheckResult(await this.callCppCheck(o),a,c);let d=a.length>0;return{content:[{type:"text",text:[c.join(`
|
|
1260
1260
|
`),a.join(`
|
|
1261
1261
|
`)].filter(b=>b.trim().length>0).join(`
|
|
1262
|
-
`).trim()||"\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return
|
|
1263
|
-
`);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{
|
|
1264
|
-
`),n=new Map;for(let i of t){if(!i)continue;let o=this.parseSearchResultLine(i);o&&n.set(o.filePath,o.count)}return n}parseSearchResultLine(e){try{let t=JSON.parse(e);if(t.type==="end"&&t.data?.path?.text){let n=t.data.stats?.matches??0;if(n>0)return{filePath:t.data.path.text,count:n}}}catch{}return null}async readDocument(e){await this.ensureInitialized();let
|
|
1262
|
+
`).trim()||"\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"}],isError:d}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return m.warn(`ArkTS check rejected: project is ${$s[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"\u9879\u76EE\u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0};case 3:return m.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleIdleCheck(){return this.ensureProjectReady(),this.config.projectPath?(m.info(`Idle check: project '${this.config.projectPath}' already known, triggering init`),{content:[{type:"text",text:"\u68C0\u6D4B\u5230\u9E3F\u8499\u5DE5\u7A0B\uFF0C\u6B63\u5728\u540C\u6B65\u4E2D\uFF0C\u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0}):this.workspaceRoot||this.originalProjectPath?(m.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"\u6B63\u5728\u521D\u59CB\u5316, \u8BF73\u79D2\u540E\u91CD\u8BD5"}],isError:!0}):(m.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"\u672A\u68C0\u6D4B\u5230\u9E3F\u8499\u5DE5\u7A0B\uFF0C\u8BF7\u786E\u8BA4\u9879\u76EE\u76EE\u5F55\u662F\u5426\u6B63\u786E\uFF0C\u6216\u5728\u9879\u76EE\u4E2D\u521B\u5EFA\u5DE5\u7A0B\u540E\u91CD\u8BD5"}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Xr?(m.error(`Init retry limit reached (${this.initRetryCount}/${Xr}), will not auto-retry`),{content:[{type:"text",text:"\u9879\u76EE\u521D\u59CB\u5316\u591A\u6B21\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u9879\u76EE\u914D\u7F6E\u540E\u91CD\u542F MCP Server"}],isError:!0}):(m.info(`Error check: auto-retrying (${this.initRetryCount}/${Xr})`),this.ensureProjectReady(),{content:[{type:"text",text:"\u9879\u76EE\u521D\u59CB\u5316\u5931\u8D25\uFF0C\u6B63\u5728\u81EA\u52A8\u91CD\u8BD5\uFF0C\u8BF75\u79D2\u540E\u91CD\u8BD5"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP \u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570\u6216\u8005\u5728DevEco Studio\u4E2D\u6253\u5F00\u9879\u76EE";return m.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
|
|
1263
|
+
`);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{m.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{m.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,m.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{m.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new Au;if(await this.server.connect(e),m.info("devecocli-mcp-server started"),!this.config.debug){let t=gs();t&&m.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 n=pe(t);n?(m.info(`Detected project path from client root: ${n}`),this.config.projectPath=n,this.sdkPath=this.computeSdkPath()):m.warn(`Client root '${t}' is not a Harmony project`)}else this.originalProjectPath?m.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no Harmony project was found in it`):m.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{m.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return m.warn("Client did not provide any roots"),null;let n=t.uri;return this.resolveFileUri(n)}catch(e){return m.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let n=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(n)?n.substring(1):n}}catch(t){m.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,m.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{m.info("shutdown completed, exiting process"),process.exit(0)}).catch(n=>{m.error("shutdown failed:",n),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){m.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new ct(e,this.config.devecoPath??null),m.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{m.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?pe(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=pe(this.originalProjectPath),t&&m.info(`Phase 1 found Harmony project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(!this.discoverProject())return;if(this.sdkPath||(this.sdkPath=this.computeSdkPath()),this.projectState=2,m.info("Starting project sync..."),!await st.handleSyncProject(this.config.projectPath,this.sdkPath)){m.error("Project sync failed"),this.initRetryCount++,this.projectState=5;return}this.projectState=3,this.arktsCheckTool=new at(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize);try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,m.info("Project fully initialized, check tool is available")}catch(t){m.error("LSP initialization failed:",t),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}computeSdkPath(){let e=en(this.config.devecoPath??""),t=se(e);return lt.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){m.warn("Failed to close MCP server connection:",e)}m.info("devecocli-mcp-server stopped"),fs(),ms()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function ku(r){let e=[],t=[],n=[];for(let i of r)lt.extname(i).toLowerCase()===".ets"?e.push(i):tn(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function Zr(r={}){return new Wn(r)}async function Mu(){let r=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE||"8192",n=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await N.new(),o=r,s=e??i.devecoStudioPath,a=Zr({projectPath:o,devecoPath:s,nodeMaxOldSpaceSize:t,debug:n}),c=async()=>{await a.shutdown(),process.exit(0)};process.once("SIGINT",c),process.once("SIGTERM",c),process.platform==="win32"&&process.once("SIGBREAK",c);try{await a.start()}catch(d){console.error("Failed to start MCP server:",d),process.exit(1)}}var _s=new Tu("serve").description("Host bundled auxiliary protocol servers");_s.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Mu()});var Ws=_s;import{Command as $u,InvalidArgumentError as ti}from"commander";import{red as Nt,dim as _u}from"colorette";import*as G from"path";import*as te from"fs";import{homedir as xu}from"os";import{execa as Ru}from"execa";import{rgPath as Ou}from"@vscode/ripgrep";import Nu from"adm-zip";import{fileURLToPath as Lu}from"url";import Hu from"ora";var Rt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Ot={"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 ju="deveco-cli",Fu="docs",Qr=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=G.join(xu(),".local","share",ju,Fu),this.versionFile=G.join(this.docsDir,".version")}getDocsDir(){return this.docsDir}async ensureInitialized(){if(!this.initialized){if(this.initPromise){await this.initPromise;return}this.initPromise=this.extractDocsIfNeeded(),await this.initPromise,this.initialized=!0}}async extractDocsIfNeeded(){let e=this.getCurrentVersion();await this.getExistingVersion()!==e&&await this.extractDocs(e)}getCurrentVersion(){return"0.6.1"}async getExistingVersion(){try{return(await te.promises.readFile(this.versionFile,"utf-8")).trim()}catch{return null}}async extractDocs(e){let t=this.findDocsZip();if(!t)throw new Error("docs.zip not found");let n=Hu({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=G.dirname(this.docsDir);await te.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await te.promises.mkdir(this.docsDir,{recursive:!0}),new Nu(t).extractAllTo(this.docsDir,!0),await te.promises.writeFile(this.versionFile,e,"utf-8"),n.succeed("Documentation extracted successfully.")}catch(i){throw n.fail("Failed to extract documentation."),i}}findDocsZip(){let e=import.meta.url,t=Lu(e),n=G.dirname(t),i=[G.join(n,"..","docs.zip")];for(let o of i)if(te.existsSync(o))return o;return null}async cleanOldDocs(){try{await te.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?G.join(this.docsDir,Ot[t]):this.docsDir,i=await this.searchFiles(e,n),o=await this.enrichWithTitleRelevance(i,e),s=this.selectByTiers(o,e.length);return(await Promise.all(s.map(async c=>{let d=this.parseFilePath(c.filePath);if(!d||!c.metadata)return null;let u=await this.readContentPreview(c.filePath);return{title:c.metadata.title,documentId:d,content:u}}))).filter(c=>c!==null)}selectByTiers(e,t){let n=(a,c)=>c.totalMatches-a.totalMatches,i=e.filter(a=>a.titleKeywordCount===t).sort(n),o=e.filter(a=>a.keywordCount===t&&a.titleKeywordCount<t).sort(n),s=e.filter(a=>a.keywordCount<t&&a.titleKeywordCount<t).sort(n);return[...i,...o,...s]}async enrichWithTitleRelevance(e,t){return Promise.all(Array.from(e.entries()).map(async([n,i])=>{let o=await this.readMetadata(n),s=o?t.filter(a=>o.title.toLowerCase().includes(a.toLowerCase())).length:0;return{filePath:n,keywordCount:i.keywordCount,totalMatches:i.totalMatches,titleKeywordCount:s,metadata:o}}))}async searchSingleKeyword(e,t){let i=await Ru(Ou,["--type","md","--json","--no-messages","-i","-e",e,t],{reject:!1});if(i.exitCode===1)return new Map;if(i.exitCode!==0)throw new Error(i.stderr?.trim()||`Search failed with exit code ${i.exitCode}`);return this.parseSearchResults(i.stdout)}async searchFiles(e,t){let n=await Promise.all(e.map(o=>this.searchSingleKeyword(o,t))),i=new Map;for(let o of n)for(let[s,a]of o){let c=i.get(s);c?(c.keywordCount+=1,c.totalMatches+=a):i.set(s,{keywordCount:1,totalMatches:a})}return i}parseSearchResults(e){let t=e.split(`
|
|
1264
|
+
`),n=new Map;for(let i of t){if(!i)continue;let o=this.parseSearchResultLine(i);o&&n.set(o.filePath,o.count)}return n}parseSearchResultLine(e){try{let t=JSON.parse(e);if(t.type==="end"&&t.data?.path?.text){let n=t.data.stats?.matches??0;if(n>0)return{filePath:t.data.path.text,count:n}}}catch{}return null}async readDocument(e){await this.ensureInitialized();let n=[e,`${e}.md`].filter(i=>E.isPathContainedWithSymlink(i,this.docsDir).contained).map(i=>G.join(this.docsDir,i));for(let i of n)try{return await te.promises.readFile(i,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=G.relative(this.docsDir,e);if(!t||t.startsWith("..")||G.isAbsolute(t))return null;let n=t.split(/[/\\]/);if(n.length<2)return null;let i=n[n.length-1];return n[n.length-1]=i.replace(/\.md$/,""),n.join("/")}async readMetadata(e){let t=e.replace(/\.md$/,".json");try{let n=await te.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await te.promises.readFile(e,"utf-8"),n=t.replace(/\n/g," ").trim().slice(0,200);return n.length<t.replace(/\n/g," ").trim().length?n+"...":n}catch{return""}}},ei=new Qr;function Us(...r){return e=>{if(!r.includes(e))throw new ti(`Allowed values: ${r.join(", ")}`);return e}}function Wu(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new ti("Must be a positive integer");return e}var Uu=Us("json","default"),Bu=Us("json","default"),Un=new $u("docs").description("Search and read Harmony documentation from local docs directory");Un.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",zu,"all").option("--format <fmt>","Output format (default, json)",Uu,"default").option("--limit <n>","Max number of results",Wu,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Nt("Keywords cannot be empty")),process.exit(1)),t.length>10&&(console.error(Nt("Keywords cannot exceed 10")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await ei.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Vu(o)}catch(t){console.error(Nt(t.message)),process.exit(1)}});Un.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Nt("Document ID cannot be empty")),process.exit(1));let t=await ei.readDocument(e);console.log(t)}catch(e){console.error(Nt(e.message)),process.exit(1)}});Un.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Bu,"default").action(r=>{if(r.format==="json"){let e=Rt.map(t=>({name:t,title:Ot[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Rt)console.log(` ${e.padEnd(20)} ${_u(Ot[e])}`)});function zu(r){if(r==="all")return"all";if(!Rt.includes(r))throw new ti(`Invalid catalog "${r}". Allowed: all, ${Rt.join(", ")}`);return r}function Vu(r){for(let e=0;e<r.length;e++){let t=r[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.content&&console.log(` Content: ${t.content}`),e<r.length-1&&console.log()}}var Bs=Un;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";qu();U.name("devecocli").description("HarmonyOS application development command line tool").version("0.6.1");U.addCommand(pi);U.addCommand(bi);U.addCommand(Di);U.addCommand(Hi);U.addCommand(ro);U.addCommand(xo);U.addCommand(Lo);U.addCommand(Vo);U.addCommand(Qo);U.addCommand(Ws);U.addCommand(Bs);var ni=process.argv.slice(2);ni.length>=2&&ni[ni.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Gu=new Set(["update"]);U.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==U;)t=t.parent;Gu.has(t.name())||await N.checkVersion()});U.parseAsync(process.argv).catch(r=>{let e=r instanceof Error?r.message:String(r??"Unknown error");console.error(Yu(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&r instanceof Error&&r.stack&&console.error(r.stack),process.exit(1)});
|