@deveco-test/deveco-cli 0.4.0 → 0.4.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.
Files changed (29) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +107 -107
  3. package/SKILL.md +119 -119
  4. package/THIRD-PARTY-LICENSES +5183 -5181
  5. package/dist/cli.js +4 -4
  6. package/package.json +2 -2
  7. package/templates/application/AppScope/app.json5 +10 -10
  8. package/templates/application/AppScope/resources/base/element/string.json +8 -8
  9. package/templates/application/AppScope/resources/base/media/layered_image.json +6 -6
  10. package/templates/application/build-profile.json5 +41 -41
  11. package/templates/application/code-linter.json5 +31 -31
  12. package/templates/application/entry/build-profile.json5 +32 -32
  13. package/templates/application/entry/hvigorfile.ts +7 -7
  14. package/templates/application/entry/obfuscation-rules.txt +19 -19
  15. package/templates/application/entry/oh-package.json5 +10 -10
  16. package/templates/application/entry/src/main/ets/entryability/EntryAbility.ets +62 -62
  17. package/templates/application/entry/src/main/ets/entrybackupability/EntryBackupAbility.ets +30 -30
  18. package/templates/application/entry/src/main/ets/pages/Index.ets +37 -37
  19. package/templates/application/entry/src/main/module.json5 +49 -49
  20. package/templates/application/entry/src/main/resources/base/element/color.json +7 -7
  21. package/templates/application/entry/src/main/resources/base/element/float.json +8 -8
  22. package/templates/application/entry/src/main/resources/base/element/string.json +15 -15
  23. package/templates/application/entry/src/main/resources/base/media/layered_image.json +6 -6
  24. package/templates/application/entry/src/main/resources/base/profile/backup_config.json +2 -2
  25. package/templates/application/entry/src/main/resources/base/profile/main_pages.json +5 -5
  26. package/templates/application/entry/src/main/resources/dark/element/color.json +7 -7
  27. package/templates/application/hvigor/hvigor-config.json5 +23 -23
  28. package/templates/application/hvigorfile.ts +7 -7
  29. package/templates/application/oh-package.json5 +10 -10
package/dist/cli.js CHANGED
@@ -26,7 +26,7 @@ Available runnable modules:
26
26
  `))}function Ca(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 Aa(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(`
27
27
  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(mi(`
28
28
  Application '${t}': ${s}`))}var ka=new ba("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 Ma(r)}catch(e){console.error(Sa(e.message)),process.exit(1)}});async function Ta(r,e,t,n,i,o){let s=new Le(e,r.rootDir),a=new Ie(e,r.rootDir),d=r.collectNonHarDependentModuleList(t).map(D=>`${D}@${n}`),u=Bn(r,d),b={type:"modules",modulesToBuild:d,moduleTasks:u};await it(r.rootDir,()=>zn(s,a,i,o,b),()=>console.log("Another build is already running for this project. Waiting for it to finish...")),console.log(`
29
- `+mi("Build completed successfully!"))}async function Ma(r){let e=De.discover(process.cwd());console.warn(Pa("Please ensure the project source is trustworthy before proceeding."));let t=await x.new(),n=Ia(e,r.module),{moduleName:i,targetName:o}=Ea(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 Ot(t),c=U.from(t),d=await Da(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),b=r.product||"default",D=r.buildMode||"debug";r.skipBuild||await Ta(e,t,i,o,b,D);let ae=Ca(e,i,o,u,b),$n=e.getBundleName(),xt=e.getMainAbility(i,r.ability);await Aa(a,d,$n,ae,xt,!!r.uninstall)}var fi=ka;import{Command as xa}from"commander";import{green as gi,red as yi,cyan as Gn}from"colorette";import{execa as vi}from"execa";function Ra(){return"@deveco-test/deveco-cli"}function Oa(){return"0.4.0"}var Na=new xa("update").description("Update deveco-cli to the latest version").action(async()=>{let r=Ra(),e=Oa();console.log(Gn("Checking for updates..."));try{let{stdout:t}=await vi("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(gi(`
29
+ `+mi("Build completed successfully!"))}async function Ma(r){let e=De.discover(process.cwd());console.warn(Pa("Please ensure the project source is trustworthy before proceeding."));let t=await x.new(),n=Ia(e,r.module),{moduleName:i,targetName:o}=Ea(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 Ot(t),c=U.from(t),d=await Da(c,r.device),u=d.includes("127.0.0.1")||d.includes("localhost"),b=r.product||"default",D=r.buildMode||"debug";r.skipBuild||await Ta(e,t,i,o,b,D);let ae=Ca(e,i,o,u,b),$n=e.getBundleName(),xt=e.getMainAbility(i,r.ability);await Aa(a,d,$n,ae,xt,!!r.uninstall)}var fi=ka;import{Command as xa}from"commander";import{green as gi,red as yi,cyan as Gn}from"colorette";import{execa as vi}from"execa";function Ra(){return"@deveco-test/deveco-cli"}function Oa(){return"0.4.1"}var Na=new xa("update").description("Update deveco-cli to the latest version").action(async()=>{let r=Ra(),e=Oa();console.log(Gn("Checking for updates..."));try{let{stdout:t}=await vi("npm",["view",r,"version"]),n=t.trim();if(n===e){console.log(gi(`
30
30
  ${r} is already up to date (version ${e})`));return}console.log(Gn(`
31
31
  New version found: ${n} (current: ${e})`)),console.log(Gn(`Updating ${r}...`)),await vi("npm",["install","-g",`${r}@latest`],{stdio:"inherit"}),console.log(`
32
32
  `+gi(`${r} updated successfully to version ${n}!`))}catch(t){let n=t;console.error(yi(`Failed to update ${r}`)),n.message&&console.error(yi(n.message)),process.exit(1)}}),wi=Na;import{Command as nc}from"commander";import{execa as Qn}from"execa";function H(r){return r.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as La}from"child_process";var Ha=2500;function Fa(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 ja(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,Ha);r.once("error",u=>c(u.message)),Fa(r,d,s,a,c,o)}function bi(r,e,t){return w(`Spawning emulator: ${r} ${t.join(" ")}`),new Promise((n,i)=>{let o=[],s=La(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)),ja(s,o,n,i)})}import*as je from"path";function $a(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 _a(r){let e=r.instancePath?.trim();if(e)return je.dirname(je.normalize(e)).replace(/\\/g,"/");let t=r.path?.trim();return t?je.dirname(je.normalize(t)).replace(/\\/g,"/"):""}function Wa(r){let e=[];return r&&e.push(["-imageRoot",r]),e.push([]),e}function Ua(r,e){let t=[["-start",r]],n=_a(e);if(n)for(let i of Wa(e.imageRoot))t.push(["-hvd",r,"-path",n,...i]);return $a(t)}async function Si(r,e,t){let n=new Error("No start strategy ran"),i=Ua(r,e);for(let o of i)try{return await t(o),{ok:!0}}catch(s){n=s}return{ok:!1,lastError:n}}async function Jn(r){return(await U.withHdcPath(r).listDevices()).map(t=>t.serial).filter(st)}async function Kn(r){let e=await Jn(r);return e.length===0?[]:(await Promise.all(e.map(n=>Yn(r,n,"ohos.qemu.hvd.name")))).filter(n=>!!n)}async function Pi(r,e){return(await Kn(r)).includes(e)}import*as $e from"path";import{existsSync as Ba,statSync as za}from"fs";function at(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function qa(r){let e=at(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 Va(r){return at(r,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Ya(r){let e=r.find(n=>n.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=$e.dirname($e.normalize(e.instancePath));for(let n of r){if(n.instancePath?.trim())continue;let i=$e.join(t,n.name);Ba(i)&&za(i).isDirectory()&&(n.instancePath=i.replace(/\\/g,"/"))}}function Ga(r){try{let e=JSON.parse(r);return Array.isArray(e)?e.map(t=>{let n=Va(t),i=at(t,["deviceType","DeviceType","devicetype"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:qa(t),path:at(t,["path","Path","hvdPath","hvd_path"]),imageRoot:at(t,["imageRoot","image_root","ImageRoot"]),uuid:n||void 0,deviceType:i||void 0}}).filter(t=>t.name):null}catch{return null}}function Ja(r){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype)\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())}}return n&&e.push(n),e}function Ei(r){let t=Ga(r)??Ja(r);return Ya(t),t}function Xn(r,e){for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim())return n.trim()}return""}function Ka(r){let e=r.downloaded??r.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Xa(r){if(!Ka(r))return null;let e=Xn(r,["osVersion","OsVersion","OSVersion"]),t=Xn(r,["SoftWareVersion","SoftwareVersion","softwareVersion"]),n=Xn(r,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:n}}function Zn(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=Xa(i);o&&n.push(o)}return n}catch{return[]}}function Di(r){let t=Zn(r).map(n=>n.osVersion).filter(Boolean);return[...new Set(t)]}var Ii=/no images are available/i;function ct(r){return r.normalize("NFKC").trim().toLowerCase()}function Za(r){let e=r.message||"";return Ii.test(e)}var _e=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 Qn(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return bi(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return Ei(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";let s=await Si(o,i,a=>this.executeEmulatorDetached(a));if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
@@ -1239,7 +1239,7 @@ Output so far:
1239
1239
  `):"\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=Q.isAbsolute(o)?o:Q.join(n,o);if(!me.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!me.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 os(500);try{let o=await this.checkFile(i);n.push(tu(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(`
1240
1240
  `)),t.length>0&&n.push(t.join(`
1241
1241
  `));let i=n.join(`
1242
- `).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(Qd),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=wt(e),n=this.popDiagnosticWaiter(t);if(n)return n;for(let i of as(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=Q.join(Zt(),"ArkTSCheck"),n=Q.join(t,"mapping-config.properties"),i=cs(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Q.join(t,"lsp-log",String(i),o),a=Q.join(t,"lsp-index",String(i));return me.mkdirSync(s,{recursive:!0}),me.mkdirSync(a,{recursive:!0}),{logPath:se(s),indexPath:se(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function tu(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 nu}from"child_process";import*as C from"fs";import*as N from"path";import{z as zr}from"zod";var js=60*1e3,ru=30*1e3,iu=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),ou=1e3,qr=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=se(this.projectPath),i=xe(n),o=N.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.4.0"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,js),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=js,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=C.realpathSync(e)}catch{t=e}let n=xe(t),i=ss(t),o=await C.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}`))},ru);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}iu.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
1242
+ `).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(Qd),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=wt(e),n=this.popDiagnosticWaiter(t);if(n)return n;for(let i of as(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=Q.join(Zt(),"ArkTSCheck"),n=Q.join(t,"mapping-config.properties"),i=cs(e,n),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Q.join(t,"lsp-log",String(i),o),a=Q.join(t,"lsp-index",String(i));return me.mkdirSync(s,{recursive:!0}),me.mkdirSync(a,{recursive:!0}),{logPath:se(s),indexPath:se(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function tu(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 nu}from"child_process";import*as C from"fs";import*as N from"path";import{z as zr}from"zod";var js=60*1e3,ru=30*1e3,iu=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),ou=1e3,qr=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=se(this.projectPath),i=xe(n),o=N.basename(n)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.4.1"},rootPath:n,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,js),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=js,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=C.realpathSync(e)}catch{t=e}let n=xe(t),i=ss(t),o=await C.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}`))},ru);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}iu.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
1243
1243
  \r
1244
1244
  `,"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
1245
1245
  \r
@@ -1252,5 +1252,5 @@ Output so far:
1252
1252
  `),s.join(`
1253
1253
  `)].filter(u=>u.trim().length>0).join(`
1254
1254
  `).trim()||"\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"}],isError:c}}async callArktsCheck(e){return!this.arktsCheckTool||!this.arktsCheckTool.isInitialized()?{content:[{type:"text",text:this.arktsCheckTool?.isInitializing()?"ArkTS LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.config.projectPath?"ArkTS LSP \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5C1D\u8BD5\u91CD\u65B0\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570\u6216\u8005\u5728DevEco Studio\u4E2D\u6253\u5F00\u9879\u76EE"}],isError:!0}:this.arktsCheckTool.handleCall({files:e})}async callCppCheck(e){return this.cppCheckTool?this.cppCheckTool.handleCall({files:e}):{content:[{type:"text",text: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"}],isError:!0}}mergeCheckResult(e,t,n){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1255
- `);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,process.env.PROJECT_PATH=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(()=>{}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(()=>{}),this.cppCheckTool=null)}async start(){this.toolRouter.registerToServer(this.server);let e=new wu;if(await this.server.connect(e),m.info("devecocli-mcp-server started"),!this.config.debug){let t=hs();t&&m.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),!this.config.projectPath){let t=await this.getProjectRootFromClient();if(t){let n=Te(t);n?(m.info(`Detected project path from client root: ${n}`),this.setProjectPath(n)):m.warn(`Client root '${t}' is not a Harmony project`)}else m.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.config.projectPath?(await this.initializeArktsCheck(),this.initializeCppCheck()):m.warn("No valid Harmony project path found, LSP tools will be unavailable")}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{}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 rt(e,this.config.devecoPath??null),m.info("CppCheckTool created (lazy initialization)")}async initializeArktsCheck(){let e=this.config.projectPath;if(!e){m.warn("LSP initialization skipped: project path is not configured");return}m.info("Initializing ArkTS LSP..."),this.config.devecoPath=Kt(this.config.devecoPath??"");let t=oe(this.config.devecoPath),n=Fn.join(t,"sdk");m.info(`devecoPath: ${this.config.devecoPath}, contentRoot: ${t}, sdkPath: ${n}`),this.arktsCheckTool=new nt(e,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),await tt.handleSyncProject(e,n);try{await this.arktsCheckTool.initialize(),m.info("ArkTS LSP initialized successfully")}catch(i){m.error("ArkTS LSP initialization failed:",i),this.arktsCheckTool=null}}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"),ps(),us()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function bu(r){let e=[],t=[],n=[];for(let i of r)Fn.extname(i).toLowerCase()===".ets"?e.push(i):Xt(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function Yr(r={}){return new Hn(r)}async function Pu(){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 x.new(),o=r,s=e??i.devecoStudioPath,a=Yr({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 Us=new Su("serve").description("Host bundled auxiliary protocol servers");Us.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Pu()});var Bs=Us;import{Command as xu,InvalidArgumentError as Kr}from"commander";import{red as Mt,dim as Ru}from"colorette";import*as J from"path";import*as ee from"fs";import{homedir as Eu}from"os";import{execa as Du}from"execa";import{rgPath as Iu}from"@vscode/ripgrep";import Cu from"adm-zip";import{fileURLToPath as Au}from"url";import ku from"ora";var kt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Tt={"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 Tu="deveco-cli",Mu="docs",Gr=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=J.join(Eu(),".local","share",Tu,Mu),this.versionFile=J.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.4.0"}async getExistingVersion(){try{return(await ee.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=ku({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=J.dirname(this.docsDir);await ee.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await ee.promises.mkdir(this.docsDir,{recursive:!0}),new Cu(t).extractAllTo(this.docsDir,!0),await ee.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=Au(e),n=J.dirname(t),i=[J.join(n,"..","docs.zip")];for(let o of i)if(ee.existsSync(o))return o;return null}async cleanOldDocs(){try{await ee.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?J.join(this.docsDir,Tt[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 Du(Iu,["--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(`
1256
- `),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 t=[J.join(this.docsDir,e),J.join(this.docsDir,`${e}.md`)];for(let n of t)try{return await ee.promises.readFile(n,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=J.relative(this.docsDir,e);if(!t||t.startsWith(".."))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 ee.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await ee.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""}}},Jr=new Gr;function zs(...r){return e=>{if(!r.includes(e))throw new Kr(`Allowed values: ${r.join(", ")}`);return e}}function Ou(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new Kr("Must be a positive integer");return e}var Nu=zs("json","default"),Lu=zs("json","default"),jn=new xu("docs").description("Search and read Harmony documentation from local docs directory");jn.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Hu,"all").option("--format <fmt>","Output format (default, json)",Nu,"default").option("--limit <n>","Max number of results",Ou,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Mt("Keywords cannot be empty")),process.exit(1)),t.length>10&&(console.error(Mt("Keywords cannot exceed 10")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await Jr.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Fu(o)}catch(t){console.error(Mt(t.message)),process.exit(1)}});jn.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Mt("Document ID cannot be empty")),process.exit(1));let t=await Jr.readDocument(e);console.log(t)}catch(e){console.error(Mt(e.message)),process.exit(1)}});jn.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Lu,"default").action(r=>{if(r.format==="json"){let e=kt.map(t=>({name:t,title:Tt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of kt)console.log(` ${e.padEnd(20)} ${Ru(Tt[e])}`)});function Hu(r){if(r==="all")return"all";if(!kt.includes(r))throw new Kr(`Invalid catalog "${r}". Allowed: all, ${kt.join(", ")}`);return r}function Fu(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 qs=jn;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";ju();W.name("devecocli").description("HarmonyOS application development command line tool").version("0.4.0");W.addCommand(ai);W.addCommand(fi);W.addCommand(wi);W.addCommand(Mi);W.addCommand(Xi);W.addCommand(Io);W.addCommand(Mo);W.addCommand(_o);W.addCommand(Jo);W.addCommand(Bs);W.addCommand(qs);var Xr=process.argv.slice(2);Xr.length>=2&&Xr[Xr.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var $u=new Set(["update"]);W.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==W;)t=t.parent;$u.has(t.name())||await x.checkVersion()});W.parseAsync(process.argv).catch(r=>{console.error(r),process.exit(1)});
1255
+ `);i&&(e.isError?t.push(i):n.push(i))}setProjectPath(e){this.config.projectPath=e,process.env.PROJECT_PATH=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(()=>{}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(()=>{}),this.cppCheckTool=null)}async start(){this.toolRouter.registerToServer(this.server);let e=new wu;if(await this.server.connect(e),m.info("devecocli-mcp-server started"),!this.config.debug){let t=hs();t&&m.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),!this.config.projectPath){let t=await this.getProjectRootFromClient();if(t){let n=Te(t);n?(m.info(`Detected project path from client root: ${n}`),this.setProjectPath(n)):m.warn(`Client root '${t}' is not a Harmony project`)}else m.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.config.projectPath?(await this.initializeArktsCheck(),this.initializeCppCheck()):m.warn("No valid Harmony project path found, LSP tools will be unavailable")}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{}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 rt(e,this.config.devecoPath??null),m.info("CppCheckTool created (lazy initialization)")}async initializeArktsCheck(){let e=this.config.projectPath;if(!e){m.warn("LSP initialization skipped: project path is not configured");return}m.info("Initializing ArkTS LSP..."),this.config.devecoPath=Kt(this.config.devecoPath??"");let t=oe(this.config.devecoPath),n=Fn.join(t,"sdk");m.info(`devecoPath: ${this.config.devecoPath}, contentRoot: ${t}, sdkPath: ${n}`),this.arktsCheckTool=new nt(e,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),await tt.handleSyncProject(e,n);try{await this.arktsCheckTool.initialize(),m.info("ArkTS LSP initialized successfully")}catch(i){m.error("ArkTS LSP initialization failed:",i),this.arktsCheckTool=null}}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"),ps(),us()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function bu(r){let e=[],t=[],n=[];for(let i of r)Fn.extname(i).toLowerCase()===".ets"?e.push(i):Xt(i)?t.push(i):n.push(i);return{etsFiles:e,cppFiles:t,unsupported:n}}function Yr(r={}){return new Hn(r)}async function Pu(){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 x.new(),o=r,s=e??i.devecoStudioPath,a=Yr({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 Us=new Su("serve").description("Host bundled auxiliary protocol servers");Us.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await Pu()});var Bs=Us;import{Command as xu,InvalidArgumentError as Kr}from"commander";import{red as Mt,dim as Ru}from"colorette";import*as J from"path";import*as ee from"fs";import{homedir as Eu}from"os";import{execa as Du}from"execa";import{rgPath as Iu}from"@vscode/ripgrep";import Cu from"adm-zip";import{fileURLToPath as Au}from"url";import ku from"ora";var kt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],Tt={"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 Tu="deveco-cli",Mu="docs",Gr=class{docsDir;versionFile;initialized=!1;initPromise=null;constructor(){this.docsDir=J.join(Eu(),".local","share",Tu,Mu),this.versionFile=J.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.4.1"}async getExistingVersion(){try{return(await ee.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=ku({text:"Extracting documentation\u2026",color:"cyan"}).start();try{let i=J.dirname(this.docsDir);await ee.promises.mkdir(i,{recursive:!0}),await this.cleanOldDocs(),await ee.promises.mkdir(this.docsDir,{recursive:!0}),new Cu(t).extractAllTo(this.docsDir,!0),await ee.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=Au(e),n=J.dirname(t),i=[J.join(n,"..","docs.zip")];for(let o of i)if(ee.existsSync(o))return o;return null}async cleanOldDocs(){try{await ee.promises.rm(this.docsDir,{recursive:!0,force:!0})}catch{}}async search(e,t){await this.ensureInitialized();let n=t?J.join(this.docsDir,Tt[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 Du(Iu,["--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(`
1256
+ `),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 t=[J.join(this.docsDir,e),J.join(this.docsDir,`${e}.md`)];for(let n of t)try{return await ee.promises.readFile(n,"utf-8")}catch{continue}throw new Error(`Document not found: ${e}`)}parseFilePath(e){if(!e.endsWith(".md"))return null;let t=J.relative(this.docsDir,e);if(!t||t.startsWith(".."))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 ee.promises.readFile(t,"utf-8");return JSON.parse(n)}catch{return null}}async readContentPreview(e){try{let t=await ee.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""}}},Jr=new Gr;function zs(...r){return e=>{if(!r.includes(e))throw new Kr(`Allowed values: ${r.join(", ")}`);return e}}function Ou(r){let e=Number(r);if(!Number.isInteger(e)||e<=0)throw new Kr("Must be a positive integer");return e}var Nu=zs("json","default"),Lu=zs("json","default"),jn=new xu("docs").description("Search and read Harmony documentation from local docs directory");jn.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Hu,"all").option("--format <fmt>","Output format (default, json)",Nu,"default").option("--limit <n>","Max number of results",Ou,20).action(async(r,e)=>{try{let t=r.map(s=>s.trim()).filter(s=>s);t.length===0&&(console.error(Mt("Keywords cannot be empty")),process.exit(1)),t.length>10&&(console.error(Mt("Keywords cannot exceed 10")),process.exit(1));let n=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=(await Jr.search(t,n)).slice(0,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Fu(o)}catch(t){console.error(Mt(t.message)),process.exit(1)}});jn.command("read <documentId>").description("Read full content of a document by document ID").action(async r=>{try{let e=r.trim();e||(console.error(Mt("Document ID cannot be empty")),process.exit(1));let t=await Jr.readDocument(e);console.log(t)}catch(e){console.error(Mt(e.message)),process.exit(1)}});jn.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Lu,"default").action(r=>{if(r.format==="json"){let e=kt.map(t=>({name:t,title:Tt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of kt)console.log(` ${e.padEnd(20)} ${Ru(Tt[e])}`)});function Hu(r){if(r==="all")return"all";if(!kt.includes(r))throw new Kr(`Invalid catalog "${r}". Allowed: all, ${kt.join(", ")}`);return r}function Fu(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 qs=jn;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";ju();W.name("devecocli").description("HarmonyOS application development command line tool").version("0.4.1");W.addCommand(ai);W.addCommand(fi);W.addCommand(wi);W.addCommand(Mi);W.addCommand(Xi);W.addCommand(Io);W.addCommand(Mo);W.addCommand(_o);W.addCommand(Jo);W.addCommand(Bs);W.addCommand(qs);var Xr=process.argv.slice(2);Xr.length>=2&&Xr[Xr.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var $u=new Set(["update"]);W.hook("preAction",async(r,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==W;)t=t.parent;$u.has(t.name())||await x.checkVersion()});W.parseAsync(process.argv).catch(r=>{console.error(r),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/deveco-cli",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -64,7 +64,7 @@
64
64
  "global-agent": "^4.1.3",
65
65
  "json5": "^2.2.3",
66
66
  "natural": "^8.1.1",
67
- "ora": "^9.4.0",
67
+ "ora": "^8.2.0",
68
68
  "proper-lockfile": "^4.1.2",
69
69
  "regedit": "^5.1.4",
70
70
  "zod": "^4.4.3"
@@ -1,10 +1,10 @@
1
- {
2
- "app": {
3
- "bundleName": "com.example.myapplication",
4
- "vendor": "example",
5
- "versionCode": 1000000,
6
- "versionName": "1.0.0",
7
- "icon": "$media:layered_image",
8
- "label": "$string:app_name"
9
- }
10
- }
1
+ {
2
+ "app": {
3
+ "bundleName": "com.example.myapplication",
4
+ "vendor": "example",
5
+ "versionCode": 1000000,
6
+ "versionName": "1.0.0",
7
+ "icon": "$media:layered_image",
8
+ "label": "$string:app_name"
9
+ }
10
+ }
@@ -1,8 +1,8 @@
1
- {
2
- "string": [
3
- {
4
- "name": "app_name",
5
- "value": "MyApplication"
6
- }
7
- ]
8
- }
1
+ {
2
+ "string": [
3
+ {
4
+ "name": "app_name",
5
+ "value": "MyApplication"
6
+ }
7
+ ]
8
+ }
@@ -1,7 +1,7 @@
1
- {
2
- "layered-image":
3
- {
4
- "background" : "$media:background",
5
- "foreground" : "$media:foreground"
6
- }
1
+ {
2
+ "layered-image":
3
+ {
4
+ "background" : "$media:background",
5
+ "foreground" : "$media:foreground"
6
+ }
7
7
  }
@@ -1,42 +1,42 @@
1
- {
2
- "app": {
3
- "signingConfigs": [],
4
- "products": [
5
- {
6
- "name": "default",
7
- "signingConfig": "default",
8
- "targetSdkVersion": "6.0.2(22)",
9
- "compatibleSdkVersion": "6.0.2(22)",
10
- "runtimeOS": "HarmonyOS",
11
- "buildOption": {
12
- "strictMode": {
13
- "caseSensitiveCheck": true,
14
- "useNormalizedOHMUrl": true
15
- }
16
- }
17
- }
18
- ],
19
- "buildModeSet": [
20
- {
21
- "name": "debug",
22
- },
23
- {
24
- "name": "release"
25
- }
26
- ]
27
- },
28
- "modules": [
29
- {
30
- "name": "entry",
31
- "srcPath": "./entry",
32
- "targets": [
33
- {
34
- "name": "default",
35
- "applyToProducts": [
36
- "default"
37
- ]
38
- }
39
- ]
40
- }
41
- ]
1
+ {
2
+ "app": {
3
+ "signingConfigs": [],
4
+ "products": [
5
+ {
6
+ "name": "default",
7
+ "signingConfig": "default",
8
+ "targetSdkVersion": "6.0.2(22)",
9
+ "compatibleSdkVersion": "6.0.2(22)",
10
+ "runtimeOS": "HarmonyOS",
11
+ "buildOption": {
12
+ "strictMode": {
13
+ "caseSensitiveCheck": true,
14
+ "useNormalizedOHMUrl": true
15
+ }
16
+ }
17
+ }
18
+ ],
19
+ "buildModeSet": [
20
+ {
21
+ "name": "debug",
22
+ },
23
+ {
24
+ "name": "release"
25
+ }
26
+ ]
27
+ },
28
+ "modules": [
29
+ {
30
+ "name": "entry",
31
+ "srcPath": "./entry",
32
+ "targets": [
33
+ {
34
+ "name": "default",
35
+ "applyToProducts": [
36
+ "default"
37
+ ]
38
+ }
39
+ ]
40
+ }
41
+ ]
42
42
  }
@@ -1,32 +1,32 @@
1
- {
2
- "files": [
3
- "**/*.ets"
4
- ],
5
- "ignore": [
6
- "**/src/ohosTest/**/*",
7
- "**/src/test/**/*",
8
- "**/src/mock/**/*",
9
- "**/node_modules/**/*",
10
- "**/oh_modules/**/*",
11
- "**/build/**/*",
12
- "**/.preview/**/*"
13
- ],
14
- "ruleSet": [
15
- "plugin:@performance/recommended",
16
- "plugin:@typescript-eslint/recommended"
17
- ],
18
- "rules": {
19
- "@security/no-unsafe-aes": "error",
20
- "@security/no-unsafe-hash": "error",
21
- "@security/no-unsafe-mac": "warn",
22
- "@security/no-unsafe-dh": "error",
23
- "@security/no-unsafe-dsa": "error",
24
- "@security/no-unsafe-ecdsa": "error",
25
- "@security/no-unsafe-rsa-encrypt": "error",
26
- "@security/no-unsafe-rsa-sign": "error",
27
- "@security/no-unsafe-rsa-key": "error",
28
- "@security/no-unsafe-dsa-key": "error",
29
- "@security/no-unsafe-dh-key": "error",
30
- "@security/no-unsafe-3des": "error"
31
- }
1
+ {
2
+ "files": [
3
+ "**/*.ets"
4
+ ],
5
+ "ignore": [
6
+ "**/src/ohosTest/**/*",
7
+ "**/src/test/**/*",
8
+ "**/src/mock/**/*",
9
+ "**/node_modules/**/*",
10
+ "**/oh_modules/**/*",
11
+ "**/build/**/*",
12
+ "**/.preview/**/*"
13
+ ],
14
+ "ruleSet": [
15
+ "plugin:@performance/recommended",
16
+ "plugin:@typescript-eslint/recommended"
17
+ ],
18
+ "rules": {
19
+ "@security/no-unsafe-aes": "error",
20
+ "@security/no-unsafe-hash": "error",
21
+ "@security/no-unsafe-mac": "warn",
22
+ "@security/no-unsafe-dh": "error",
23
+ "@security/no-unsafe-dsa": "error",
24
+ "@security/no-unsafe-ecdsa": "error",
25
+ "@security/no-unsafe-rsa-encrypt": "error",
26
+ "@security/no-unsafe-rsa-sign": "error",
27
+ "@security/no-unsafe-rsa-key": "error",
28
+ "@security/no-unsafe-dsa-key": "error",
29
+ "@security/no-unsafe-dh-key": "error",
30
+ "@security/no-unsafe-3des": "error"
31
+ }
32
32
  }
@@ -1,33 +1,33 @@
1
- {
2
- "apiType": "stageMode",
3
- "buildOption": {
4
- "resOptions": {
5
- "copyCodeResource": {
6
- "enable": false
7
- }
8
- }
9
- },
10
- "buildOptionSet": [
11
- {
12
- "name": "release",
13
- "arkOptions": {
14
- "obfuscation": {
15
- "ruleOptions": {
16
- "enable": false,
17
- "files": [
18
- "./obfuscation-rules.txt"
19
- ]
20
- }
21
- }
22
- }
23
- },
24
- ],
25
- "targets": [
26
- {
27
- "name": "default"
28
- },
29
- {
30
- "name": "ohosTest",
31
- }
32
- ]
1
+ {
2
+ "apiType": "stageMode",
3
+ "buildOption": {
4
+ "resOptions": {
5
+ "copyCodeResource": {
6
+ "enable": false
7
+ }
8
+ }
9
+ },
10
+ "buildOptionSet": [
11
+ {
12
+ "name": "release",
13
+ "arkOptions": {
14
+ "obfuscation": {
15
+ "ruleOptions": {
16
+ "enable": false,
17
+ "files": [
18
+ "./obfuscation-rules.txt"
19
+ ]
20
+ }
21
+ }
22
+ }
23
+ },
24
+ ],
25
+ "targets": [
26
+ {
27
+ "name": "default"
28
+ },
29
+ {
30
+ "name": "ohosTest",
31
+ }
32
+ ]
33
33
  }
@@ -1,7 +1,7 @@
1
- // @ts-nocheck – Template file, only used when copied into a project directory
2
- import { hapTasks } from '@ohos/hvigor-ohos-plugin';
3
-
4
- export default {
5
- system: hapTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
6
- plugins: [] /* Custom plugin to extend the functionality of Hvigor. */,
7
- };
1
+ // @ts-nocheck – Template file, only used when copied into a project directory
2
+ import { hapTasks } from '@ohos/hvigor-ohos-plugin';
3
+
4
+ export default {
5
+ system: hapTasks /* Built-in plugin of Hvigor. It cannot be modified. */,
6
+ plugins: [] /* Custom plugin to extend the functionality of Hvigor. */,
7
+ };
@@ -1,20 +1,20 @@
1
- # Define project specific obfuscation rules here.
2
- # You can include the obfuscation configuration files in the current module's build-profile.json5.
3
-
4
- # Obfuscation options:
5
- # -disable-obfuscation: disable all obfuscations
6
- # -enable-property-obfuscation: obfuscate the property names
7
- # -enable-toplevel-obfuscation: obfuscate the names in the global scope
8
- # -compact: remove unnecessary blank spaces and all line feeds
9
- # -remove-log: remove all console.* statements
10
- # -print-namecache: print the name cache that contains the mapping from the old names to new names
11
- # -apply-namecache: reuse the given cache file
12
-
13
- # Keep options:
14
- # -keep-property-name: specifies property names that you want to keep
15
- # -keep-global-name: specifies names that you want to keep in the global scope
16
-
17
- -enable-property-obfuscation
18
- -enable-toplevel-obfuscation
19
- -enable-filename-obfuscation
1
+ # Define project specific obfuscation rules here.
2
+ # You can include the obfuscation configuration files in the current module's build-profile.json5.
3
+
4
+ # Obfuscation options:
5
+ # -disable-obfuscation: disable all obfuscations
6
+ # -enable-property-obfuscation: obfuscate the property names
7
+ # -enable-toplevel-obfuscation: obfuscate the names in the global scope
8
+ # -compact: remove unnecessary blank spaces and all line feeds
9
+ # -remove-log: remove all console.* statements
10
+ # -print-namecache: print the name cache that contains the mapping from the old names to new names
11
+ # -apply-namecache: reuse the given cache file
12
+
13
+ # Keep options:
14
+ # -keep-property-name: specifies property names that you want to keep
15
+ # -keep-global-name: specifies names that you want to keep in the global scope
16
+
17
+ -enable-property-obfuscation
18
+ -enable-toplevel-obfuscation
19
+ -enable-filename-obfuscation
20
20
  -enable-export-obfuscation
@@ -1,10 +1,10 @@
1
- {
2
- "name": "entry",
3
- "version": "1.0.0",
4
- "description": "Please describe the basic information.",
5
- "main": "",
6
- "author": "",
7
- "license": "",
8
- "dependencies": {}
9
- }
10
-
1
+ {
2
+ "name": "entry",
3
+ "version": "1.0.0",
4
+ "description": "Please describe the basic information.",
5
+ "main": "",
6
+ "author": "",
7
+ "license": "",
8
+ "dependencies": {}
9
+ }
10
+
@@ -1,63 +1,63 @@
1
- /*
2
- * Copyright (c) 2026 Huawei Device Co., Ltd.
3
- * Licensed under the Apache License, Version 2.0 (the "License");
4
- * you may not use this file except in compliance with the License.
5
- * You may obtain a copy of the License at
6
- *
7
- * http://www.apache.org/licenses/LICENSE-2.0
8
- *
9
- * Unless required by applicable law or agreed to in writing, software
10
- * distributed under the License is distributed on an "AS IS" BASIS,
11
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- * See the License for the specific language governing permissions and
13
- * limitations under the License.
14
- */
15
-
16
- import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
17
- import { hilog } from '@kit.PerformanceAnalysisKit';
18
- import { window } from '@kit.ArkUI';
19
-
20
- const DOMAIN = 0x0000;
21
-
22
- export default class EntryAbility extends UIAbility {
23
- onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
24
- try {
25
- this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
26
- } catch (err) {
27
- hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
28
- }
29
- hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
30
- }
31
-
32
- onDestroy(): void {
33
- hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
34
- }
35
-
36
- onWindowStageCreate(windowStage: window.WindowStage): void {
37
- // Main window is created, set main page for this ability
38
- hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
39
-
40
- windowStage.loadContent('pages/Index', (err) => {
41
- if (err.code) {
42
- hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
43
- return;
44
- }
45
- hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
46
- });
47
- }
48
-
49
- onWindowStageDestroy(): void {
50
- // Main window is destroyed, release UI related resources
51
- hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
52
- }
53
-
54
- onForeground(): void {
55
- // Ability has brought to foreground
56
- hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
57
- }
58
-
59
- onBackground(): void {
60
- // Ability has back to background
61
- hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
62
- }
1
+ /*
2
+ * Copyright (c) 2026 Huawei Device Co., Ltd.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ *
7
+ * http://www.apache.org/licenses/LICENSE-2.0
8
+ *
9
+ * Unless required by applicable law or agreed to in writing, software
10
+ * distributed under the License is distributed on an "AS IS" BASIS,
11
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ * See the License for the specific language governing permissions and
13
+ * limitations under the License.
14
+ */
15
+
16
+ import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
17
+ import { hilog } from '@kit.PerformanceAnalysisKit';
18
+ import { window } from '@kit.ArkUI';
19
+
20
+ const DOMAIN = 0x0000;
21
+
22
+ export default class EntryAbility extends UIAbility {
23
+ onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
24
+ try {
25
+ this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
26
+ } catch (err) {
27
+ hilog.error(DOMAIN, 'testTag', 'Failed to set colorMode. Cause: %{public}s', JSON.stringify(err));
28
+ }
29
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
30
+ }
31
+
32
+ onDestroy(): void {
33
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
34
+ }
35
+
36
+ onWindowStageCreate(windowStage: window.WindowStage): void {
37
+ // Main window is created, set main page for this ability
38
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
39
+
40
+ windowStage.loadContent('pages/Index', (err) => {
41
+ if (err.code) {
42
+ hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
43
+ return;
44
+ }
45
+ hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
46
+ });
47
+ }
48
+
49
+ onWindowStageDestroy(): void {
50
+ // Main window is destroyed, release UI related resources
51
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
52
+ }
53
+
54
+ onForeground(): void {
55
+ // Ability has brought to foreground
56
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
57
+ }
58
+
59
+ onBackground(): void {
60
+ // Ability has back to background
61
+ hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
62
+ }
63
63
  }