@deveco-test/hmos-deveco-cli 0.1.0-TD.5 → 0.1.0-TD.5.1-alpha1

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 CHANGED
@@ -52,7 +52,7 @@ Available runnable modules:
52
52
  Installing artifacts to device ${e}...`),await n.installApp(e,r),o){console.log(`Launching ${t}/${o}...`);let s=await n.launchApp(e,t,o);console.log(Ys(`
53
53
  Application '${t}': ${s}`))}else console.log(`
54
54
  Application '${t}' installed successfully (no ability to launch).`)}var Rp=new Ip("run").description("Build and run the project on a connected device").option("--module <modules...>","Module(s) to run (format: module or module@target)").option("--device <device>","Target device name or serial").option("--product <product>","Product name (default: default)").option("--build-mode <mode>","Build mode (options: debug, release; default: debug)").option("--ability <ability>","Ability name to launch").option("--uninstall","Uninstall existing app before installation").option("--skip-build","Skip build step and deploy existing artifacts").option("--preview","Launch DevEco Studio previewer instead of installing/running the app").option("--count <n>","Previewer only: number of previewer windows to launch (multi-previewer mode)").option("--devices <names>",`Previewer only: comma-separated device product names (e.g. "Pura 90 Pro,MatePad 11.5'S"). Takes priority over --count`).action(async n=>{try{await Hp(n)}catch(e){console.error(Dp(e.message)),process.exit(1)}});async function Op(n,e,t,r,o){let i=new Oe(e,n.rootDir),s=new be(e,n.rootDir),a=new Set;for(let{moduleName:h,targetName:v}of t)for(let I of n.collectNonHarDependentModuleList(h))a.add(`${I}@${v}`);let c=[...a],l=qt(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Xe(n.rootDir,()=>Vt(i,s,r,o,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
55
- `+Ys("Build completed successfully."))}async function Np(n,e,t,r,o){let i=new Jt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function Lp(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}function _p(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function Hp(n){let e=Ze.discover(process.cwd());console.warn(Cp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=xp(e,n.module),o=r.map(Ap);if(n.preview){await Np(n,e,t,o,r);return}Lp(e,o);let i=new Jt(t),s=K.from(t),a=await Tp(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let u=n.buildMode||"debug";n.skipBuild||await Op(e,t,o,l,u);let h=_p(e,o,c,l),v=e.getBundleName(),I=kp(e,o,n.ability);await Mp(i,a,v,h,I,!!n.uninstall)}var Js=Rp;import{Command as jp}from"commander";import{green as Ks,red as Zs,cyan as Lo}from"colorette";import{execa as Xs}from"execa";function Fp(){return"@deveco-test/hmos-deveco-cli"}function $p(){return"0.1.0-TD.5"}var Bp=new jp("update").description("Update deveco-cli to latest").action(async()=>{let n=Fp(),e=$p();console.log(Lo("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
55
+ `+Ys("Build completed successfully."))}async function Np(n,e,t,r,o){let i=new Jt(t),s=K.from(t),a=r[0]?.moduleName||o[0];await Gs(n,e,t,i,s,a)||process.exit(1)}function Lp(n,e){for(let{moduleName:t}of e){let r=n.getModuleType(t);if(r!=="entry"&&r!=="feature"&&r!=="shared")throw new Error(`Module '${t}' '${r}' is not runnable. Specify an entry or feature module.`)}}function _p(n,e,t,r){let o=new Set;for(let{moduleName:i,targetName:s}of e){let a=n.collectNonHarDependentModuleList(i);for(let c of a)o.add(n.findArtifactPath(c,s,t,r));o.add(n.findArtifactPath(i,s,t,r))}return[...o]}async function Hp(n){let e=Ze.discover(process.cwd());console.warn(Cp("Ensure the project source is trusted before proceeding."));let t=await _.new(),r=xp(e,n.module),o=r.map(Ap);if(n.preview){await Np(n,e,t,o,r);return}Lp(e,o);let i=new Jt(t),s=K.from(t),a=await Tp(s,n.device),c=a.includes("127.0.0.1")||a.includes("localhost"),l=n.product||"default";e.validateProduct(l);let u=n.buildMode||"debug";n.skipBuild||await Op(e,t,o,l,u);let h=_p(e,o,c,l),v=e.getBundleName(),I=kp(e,o,n.ability);await Mp(i,a,v,h,I,!!n.uninstall)}var Js=Rp;import{Command as jp}from"commander";import{green as Ks,red as Zs,cyan as Lo}from"colorette";import{execa as Xs}from"execa";function Fp(){return"@deveco-test/hmos-deveco-cli"}function $p(){return"0.1.0-TD.5.1-alpha1"}var Bp=new jp("update").description("Update deveco-cli to latest").action(async()=>{let n=Fp(),e=$p();console.log(Lo("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
56
56
  ${n} is already up to date (version ${e}.)`));return}console.log(Lo(`
57
57
  New version found: ${r} (current: ${e})`)),console.log(Lo(`Updating ${n}...`)),await Xs("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
58
58
  `+Ks(`${n} updated successfully to version ${r}.`))}catch(t){let r=t;console.error(Zs(`Failed to update ${n}`)),r.message&&console.error(Zs(r.message)),process.exit(1)}}),Qs=Bp;import{Command as lm}from"commander";import{execa as Fo}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Wp}from"child_process";var Up=2500;function zp(n,e,t,r,o,i){n.once("exit",s=>{if(i())return;clearTimeout(e);let a=t();s===0||s===null?r():o(a||`Emulator process exited with code ${s}`)})}function qp(n,e,t,r){let o=!1,i=()=>o,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{o||(o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!o){o=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Up);n.once("error",u=>c(u.message)),zp(n,l,s,a,c,i)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,o)=>{let i=[],s=Wp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>i.push(a)),qp(s,i,r,o)})}import*as gt from"path";function Vp(n){let e=new Set,t=[];for(let r of n){let o=JSON.stringify(r);e.has(o)||(e.add(o),t.push(r))}return t}function Gp(n){let e=n.instancePath?.trim();if(e)return gt.dirname(gt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?gt.dirname(gt.normalize(t)).replace(/\\/g,"/"):""}function Yp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Jp(n,e,t){let r=[ta(["-start",n],t)],o=Gp(e);if(o)for(let i of Yp(e.imageRoot))r.push(ta(["-hvd",n,"-path",o,...i],t));return Vp(r)}async function na(n,e,t,r){let o=new Error("No start strategy ran"),i=Jp(n,e,r);for(let s of i)try{return await t(s),{ok:!0}}catch(a){o=a}return{ok:!1,lastError:o}}async function _o(n){return(await K.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Yt)}async function Ho(n){let e=await _o(n);return e.length===0?[]:(await Promise.all(e.map(r=>Wn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await Ho(n)).includes(e)}import*as vt from"path";import{existsSync as Kp,statSync as Zp}from"fs";function yt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Xp(n){let e=yt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=t.toLowerCase();if(o.includes("instance")&&(o.includes("path")||o.includes("dir"))||o==="deployedpath")return r.trim()}return""}function Qp(n){return yt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function em(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=vt.dirname(vt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let o=vt.join(t,r.name);Kp(o)&&Zp(o).isDirectory()&&(r.instancePath=o.replace(/\\/g,"/"))}}function tm(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=Qp(t),o=yt(t,["deviceType","DeviceType","devicetype"]),i=yt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Xp(t),path:yt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:yt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:o||void 0,osVersion:i||void 0}}).filter(t=>t.name):null}catch{return null}}function nm(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,o;for(;(o=t.exec(n))!==null;){let[,i,s]=o;if(i.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=i.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function oa(n){let t=tm(n)??nm(n);return em(t),t}function jo(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function rm(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function om(n){if(!rm(n))return null;let e=jo(n,["osVersion","OsVersion","OSVersion"]),t=jo(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=jo(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Vn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let o of t){if(!o||typeof o!="object")continue;let i=om(o);i&&r.push(i)}return r}catch{return[]}}function ia(n){let t=Vn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i;function he(n){return n.normalize("NFKC").trim().toLowerCase()}function im(n){let e=n.message||"";return sa.test(e)}var wt=class n{emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return Fo(this.emulatorPath,e,{stdio:["ignore","pipe","pipe"],env:{...process.env,DEVECO_SDK_HOME:this.sdkPath}})}executeEmulatorDetached(e){return ea(this.emulatorPath,this.sdkPath,e)}async listEmulators(){let{stdout:e}=await this.executeEmulator(["-list","-details"]);return oa(e)}async getDeviceTypeByName(){let e=new Map;try{let t=await this.listEmulators();for(let r of t)r.name&&r.deviceType&&e.set(V(r.name),r.deviceType)}catch{}return e}async startEmulator(e){let t=await this.listEmulators(),r=V(e),o=t.find(a=>V(a.name)===r);if(!o)throw new Error(`Emulator "${e}" not found.`);let i=o.name;if(await this.isAlreadyRunning(i,o))return"already-running";await this.assertSystemImageAvailable(o);let s=await na(i,o,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(i))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
@@ -1269,7 +1269,7 @@ Output so far:
1269
1269
  `):"\u6CA1\u6709\u6709\u6548\u7684 .ets \u6587\u4EF6"}],isError:!0}:(await this.runDiagnosticsForFiles(o,t,r),this.formatCallResult(t,r))}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,o=[];for(let i of e){let s=we.isAbsolute(i)?i:we.join(r,i);if(!xe.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${i}`);continue}if(!xe.statSync(s).isFile()){t.push(`\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${i}`);continue}if(!s.endsWith(".ets")){t.push(`\u4E0D\u662F .ets \u6587\u4EF6: ${i}`);continue}o.push(s)}return o}async runDiagnosticsForFiles(e,t,r){for(let o of e){await Ac(500);try{let i=await this.checkFile(o);r.push(mg(o,i))}catch(i){t.push(`${o} => wait for diagnostics failed: ${i.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1270
1270
  `)),t.length>0&&r.push(t.join(`
1271
1271
  `));let o=r.join(`
1272
- `).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of xc(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=kc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function mg(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import{spawn as fg}from"child_process";import*as C from"fs";import*as Z from"path";import{z as Ci}from"zod";var il=60*1e3,hg=30*1e3,gg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),yg=1e3,Ti=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.5"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,il),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=il,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Tc(t),i=await C.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},hg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{f.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}gg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
1272
+ `).trim(),i=e.length>0;return!i&&t.length===0&&(o="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:o}],isError:i}}async shutdown(){if(this.failAllPending(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(e){f.warn(`Failed to dispose ArktsLspManager: ${e}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null,this.clearInitHandlers()}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":case"textDocument/didOpen":this.handleDiagnosticsNotification(t.params);break;case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(un),f.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{f.info("Received arkts/initialized");let o=this.initResolve;this.clearInitHandlers(),o?.();break}case"arkts/initializationFailed":{let i=t.params?.message??"unknown";f.error(`LSP initialization failed: ${i}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${i}`));break}case"workspace/didChangeConfiguration":f.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.resolveDiagnosticWaiter(t);if(!r)return;if(typeof e.errorMessage=="string"){f.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let o=e.diagnostics,i=Array.isArray(o)?o.length:0;f.debug(`diagnostics received uri=${t} count=${i}`),r.resolve(Array.isArray(o)?o:[])}resolveDiagnosticWaiter(e){let t=ln(e),r=this.popDiagnosticWaiter(t);if(r)return r;for(let o of xc(e)){let i=this.popDiagnosticWaiter(o);if(i)return i}}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}failAllPending(e){for(let[,r]of this.diagnosticWaiters)clearTimeout(r.timer),r.reject(e);this.diagnosticWaiters.clear();let t=this.initReject;this.clearInitHandlers(),t?.(e)}getLogAndIndexPath(e){try{let t=we.join(lr(),"ArkTSCheck"),r=we.join(t,"mapping-config.properties"),o=kc(e,r),i=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=we.join(t,"lsp-log",String(o),i),a=we.join(t,"lsp-index",String(o));return xe.mkdirSync(s,{recursive:!0}),xe.mkdirSync(a,{recursive:!0}),{logPath:ve(s),indexPath:ve(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function mg(n,e){if(Array.isArray(e))return e.length===0?`${n} => no diagnostics`:`${n} => Diagnostic: ${JSON.stringify(e)}`;if(e&&typeof e=="object"&&typeof e.errorMessage=="string"){let t=e.errorMessage;return`${n} diagnostic failed, error_message: ${t}`}return`${n} => diagnostic failed, result: ${JSON.stringify(e)}`}import{spawn as fg}from"child_process";import*as C from"fs";import*as Z from"path";import{z as Ci}from"zod";var il=60*1e3,hg=30*1e3,gg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),yg=1e3,Ti=class{nextRequestId=1;pendingRequests=new Map;diagnosticWaiters=new Map;fileCheckLock=Promise.resolve();closed=!1;wrapperState="preInitialize";queuedDocumentNotifications=[];backendReady=!1;projectPath=null;clangdStdin=null;clangdStdout=null;clangdBuffer=Buffer.alloc(0);constructor(){}isClosed(){return this.closed}async initialize(e){this.projectPath=e,this.wrapperState="waitingForDatabase"}async connectClangdProcess(e,t){if(this.closed)throw new Error("Client is already closed");this.clangdStdin=e,this.clangdStdout=t,this.wrapperState="startingBackend",this.clangdStdout.on("data",a=>this.handleClangdData(a)),this.clangdStdout.on("error",a=>{f.warn(`[CppCheck] clangd stdout error: ${a}`),this.failAll(new Error(`clangd stdout error: ${a}`))}),this.clangdStdout.on("end",()=>{this.failAll(new Error("C++ language server connection closed"))});let r=ve(this.projectPath),o=rt(r),i=Z.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"0.1.0-TD.5.1-alpha1"},rootPath:r,rootUri:o,workspaceFolders:[{uri:o,name:i}],capabilities:{}};await this.sendRequestToClangd("initialize",s,il),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,f.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=il,t=Date.now();for(;!this.backendReady&&!this.closed&&Date.now()-t<e;)await new Promise(r=>setTimeout(r,500));if(!this.backendReady)throw new Error("Timed out waiting for clangd backend to be ready")}async checkFile(e){await this.waitForBackendReady();let t=await this.acquireFileCheckLock();try{return await this.doCheckFile(e)}finally{t()}}async doCheckFile(e){let t;try{t=C.realpathSync(e)}catch{t=e}let r=rt(t),o=Tc(t),i=await C.promises.readFile(t,"utf8"),s=new Promise((a,c)=>{let l=setTimeout(()=>{this.diagnosticWaiters.delete(r)&&c(new Error(`Timed out waiting for diagnostics: ${e}`))},hg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:o,version:1,text:i}})}catch(a){let c=this.diagnosticWaiters.get(r);throw c&&(clearTimeout(c.timer),this.diagnosticWaiters.delete(r)),a}try{return await s}finally{await this.closeFile(r).catch(a=>{f.warn(`[CppCheck] didClose failed for ${r}: ${a}`)})}}async close(){if(!this.closed&&(this.closed=!0,this.wrapperState="shuttingDown",this.backendReady&&this.clangdStdin)){try{await this.sendRequestToClangd("shutdown",null,3e3)}catch(e){f.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){f.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){f.warn(`[CppCheck] stdin.end() failed: ${e}`)}}}async sendNotification(e,t){let r={jsonrpc:"2.0",method:e,params:t??void 0};if(this.backendReady&&this.clangdStdin){await this.writeToClangd(r);return}gg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){let o=this.nextRequestId++;return new Promise((i,s)=>{let a=setTimeout(()=>{this.pendingRequests.delete(o)&&s(new Error(`Timed out waiting for ${e} response`))},r);this.pendingRequests.set(o,{resolve:i,reject:s,timer:a}),this.writeToClangd({jsonrpc:"2.0",id:o,method:e,params:t??void 0}).catch(c=>{this.pendingRequests.delete(o)&&(clearTimeout(a),s(c))})})}async sendNotificationToClangd(e,t){await this.writeToClangd({jsonrpc:"2.0",method:e,params:t??void 0})}async writeToClangd(e){if(!this.clangdStdin)throw new Error("clangd stdin not available");return new Promise((t,r)=>{let o;try{o=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let i=Buffer.from(o,"utf8"),s=Buffer.from(`Content-Length: ${i.length}\r
1273
1273
  \r
1274
1274
  `,"ascii"),a=!1,c=u=>{a||(a=!0,u?r(u):t())};if(this.clangdStdin.write(Buffer.concat([s,i]),u=>{u?c(u):a||c()}))c();else{let u=()=>c();this.clangdStdin.once("drain",u)}})}handleClangdData(e){for(this.clangdBuffer=this.clangdBuffer.length===0?e:Buffer.concat([this.clangdBuffer,e]);;){let t=this.clangdBuffer.indexOf(`\r
1275
1275
  \r
@@ -1355,4 +1355,4 @@ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1355
1355
  Detail: ${n.message}`):n}try{await Je()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(`${yw()}
1356
1356
 
1357
1357
  Detail: ${e}`)}try{await Rn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new Ln(vw(e))}}var fs=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function Sw(n){return new Promise(e=>setTimeout(e,n))}async function Pw(n){let e=jt();await z.promises.mkdir(Bt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1358
- `)}async function Ew(n){let e=Ve();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new ww(e).extractAllTo(n,!0),await hu(n)}async function Iw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function Dw(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await td(n),e&&(e.text="Documentation index installed.")}async function Cw(n,e,t){let r=Ht(),o=await fu();await z.promises.mkdir(X(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ye({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await Ew(o),await mu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ye({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Iw(),Wd()}async function yu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Aw(n){let e=await Gi(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ye({state:"done",message:t,error:null})}async function Tw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await Pw(`ERROR: ${t}`),e?.fail(t),n}async function xw(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=Wl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function kw(){let n=await xw();return bw.lock(n,{stale:1800*1e3})}async function Mw(){let n=Ve(),e=(n?await to(n):null)??await Vi();if(!e)throw new Error("docs.zip not found");return e}async function Rw(n,e){let t=await Mw(),r=n.force||await Ji(n.force),o=await Yi(n.force);if(!r&&!o&&Dn()){await Aw(e);return}if(Wi()&&!n.force){await Dw(t,e),await yu(e);return}await Cw(n,t,e),await yu(e)}var hs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:wu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await kw(),await qi(sd("Starting documentation setup\u2026")),await Rw(e,o)}catch(s){return Tw(s,o)}finally{i&&await i()}}};async function Ow(n){for(;;){let e=await oo();if(e.state==="done"&&Dn())return;if(e.state==="error")throw new fs("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");n.text=e.message||"Documentation is being prepared\u2026",await Sw(500)}}async function vu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await hs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Nw(){if(Dn())return;let n=wu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ad()){await Ow(n),n.succeed("Documentation ready.");return}if(await Ji()){await vu(n),n.succeed("Documentation ready.");return}await vu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Nw(),await gu()}var gs=class{async search(e,t,r=20){return await _n(),qd(e,t,r)}async readDocument(e){return await _n(),Xl(e)}},ys=new gs;function bu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Hw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var jw=bu("json","default"),Fw=bu("json","default"),Po=new Lw("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Bw,"all").option("--format <fmt>","Output format (default, json)",jw,"default").option("--limit <n>","Max number of results",Hw,20).action(async(n,e)=>{try{let t=$w(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Ww(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Fw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=ze.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of ze)console.log(` ${e.padEnd(20)} ${_w(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function $w(n){let e=n.map(r=>r.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>Sn)throw new Error(`Query exceeds ${Sn} characters.`);return e}function Bw(n){if(n==="all")return"all";if(!ze.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${ze.join(", ")}`);return n}function Ww(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var Su=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Uw();Q.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.5");Q.addCommand(_s);Q.addCommand(Js);Q.addCommand(Qs);Q.addCommand(ua);D()||Q.addCommand(Ra);Q.addCommand(rc);Q.addCommand(cc);Q.addCommand(yc);Q.addCommand(Dc);Q.addCommand(ml);Q.addCommand(Su);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var qw=new Set(["update"]);Q.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Q;)t=t.parent;qw.has(t.name())||await _.checkVersion()});Q.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(zw(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
1358
+ `)}async function Ew(n){let e=Ve();if(!e)throw new Error("docs.zip not found");await z.promises.rm(n,{recursive:!0,force:!0}),await z.promises.mkdir(n,{recursive:!0}),new ww(e).extractAllTo(n,!0),await hu(n)}async function Iw(){let n=X(),e=Ht(),t=await z.promises.readdir(e);for(let r of t){let o=Bt.join(n,r);await z.promises.rm(o,{force:!0}),await z.promises.rename(Bt.join(e,r),o)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Bt.join(n,"orama.dpack"),{force:!0})}async function Dw(n,e){e?.start("Installing documentation index\u2026"),await Ye({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await td(n),e&&(e.text="Documentation index installed.")}async function Cw(n,e,t){let r=Ht(),o=await fu();await z.promises.mkdir(X(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ye({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await Ew(o),await mu({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:ro(),synonymsHash:no(),builtBy:n.builtBy??"doc-init",onProgress:async i=>{t&&(t.text=i.message),await Ye({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await z.promises.rm(o,{recursive:!0,force:!0})}await Ye({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await Iw(),Wd()}async function yu(n){await Ye({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function Aw(n){let e=await Gi(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ye({state:"done",message:t,error:null})}async function Tw(n,e){let t=n instanceof Error?n.message:String(n);throw await Ye({state:"error",error:t}),await Pw(`ERROR: ${t}`),e?.fail(t),n}async function xw(){let n=X();await z.promises.mkdir(n,{recursive:!0});let e=Wl();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function kw(){let n=await xw();return bw.lock(n,{stale:1800*1e3})}async function Mw(){let n=Ve(),e=(n?await to(n):null)??await Vi();if(!e)throw new Error("docs.zip not found");return e}async function Rw(n,e){let t=await Mw(),r=n.force||await Ji(n.force),o=await Yi(n.force);if(!r&&!o&&Dn()){await Aw(e);return}if(Wi()&&!n.force){await Dw(t,e),await yu(e);return}await Cw(n,t,e),await yu(e)}var hs=class{static async run(e={}){let t=e.background??!1,o=e.quiet??t?void 0:wu({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await kw(),await qi(sd("Starting documentation setup\u2026")),await Rw(e,o)}catch(s){await Tw(s,o)}finally{i&&await i()}}};async function Ow(n){for(;;){let e=await oo();if(e.state==="done"&&Dn())return;if(e.state==="error")throw new fs("build-failed",e.error??"Documentation setup failed. Try your docs command again in a moment.");n.text=e.message||"Documentation is being prepared\u2026",await Sw(500)}}async function vu(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await hs.run({builtBy:"doc-init",force:e,quiet:!0})}async function Nw(){if(Dn())return;let n=wu({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await ad()){await Ow(n),n.succeed("Documentation ready.");return}if(await Ji()){await vu(n),n.succeed("Documentation ready.");return}await vu(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function _n(){await Nw(),await gu()}var gs=class{async search(e,t,r=20){return await _n(),qd(e,t,r)}async readDocument(e){return await _n(),Xl(e)}},ys=new gs;function bu(...n){return e=>{if(!n.includes(e))throw new vs(`Allowed values: ${n.join(", ")}`);return e}}function Hw(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new vs("Must be a positive integer.");return e}var jw=bu("json","default"),Fw=bu("json","default"),Po=new Lw("docs").description("Search and read HarmonyOS documentation from local docs directory");Po.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Bw,"all").option("--format <fmt>","Output format (default, json)",jw,"default").option("--limit <n>","Max number of results",Hw,20).action(async(n,e)=>{try{let t=$w(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,o=await ys.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(o,null,2)):Ww(o)}catch(t){console.error(So(t.message)),process.exit(1)}});Po.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(So("Document ID cannot be empty.")),process.exit(1));let t=await ys.readDocument(e);console.log(t)}catch(e){console.error(So(e.message)),process.exit(1)}});Po.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Fw,"default").action(async n=>{try{if(await _n(),n.format==="json"){let e=ze.map(t=>({name:t,title:at[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of ze)console.log(` ${e.padEnd(20)} ${_w(at[e])}`)}catch(e){console.error(So(e.message)),process.exit(1)}});function $w(n){let e=n.map(r=>r.trim()).filter(Boolean);if(e.length===0)throw new Error("Keywords cannot be empty.");if(e.join(" ").length>Sn)throw new Error(`Query exceeds ${Sn} characters.`);return e}function Bw(n){if(n==="all")return"all";if(!ze.includes(n))throw new vs(`Invalid catalog "${n}". Allowed: all, ${ze.join(", ")}`);return n}function Ww(n){for(let e=0;e<n.length;e++){let t=n[e];console.log(t.documentId),console.log(` Title: ${t.title}`),t.snippet&&console.log(` Content: ${t.snippet}`),e<n.length-1&&console.log()}}var Su=Po;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Uw();Q.name("devecocli").description("HarmonyOS application development command line tool").version("0.1.0-TD.5.1-alpha1");Q.addCommand(_s);Q.addCommand(Js);Q.addCommand(Qs);Q.addCommand(ua);D()||Q.addCommand(Ra);Q.addCommand(rc);Q.addCommand(cc);Q.addCommand(yc);Q.addCommand(Dc);Q.addCommand(ml);Q.addCommand(Su);var ws=process.argv.slice(2);ws.length>=2&&ws[ws.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var qw=new Set(["update"]);Q.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==Q;)t=t.parent;qw.has(t.name())||await _.checkVersion()});Q.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(zw(`Error: ${e}`)),process.env.DEVECO_CLI_DEBUG==="1"&&n instanceof Error&&n.stack&&console.error(n.stack),process.exit(1)});
@@ -62,4 +62,4 @@ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
62
62
  INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
63
63
  VALUES (?, ?, ?, ?, ?)
64
64
  `),a=n.length;for(let c=0;c<a;c+=B){let f=n.slice(c,c+B),p=await Promise.all(f.map(async E=>({source:E,searchText:await ot(E)})));o.transaction(E=>{for(let g of E){let A=to(o,i,g.source);s.run(A,g.source.sectionTitle,g.source.leadText,g.searchText,g.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function no(t,e,n,r,o,i,s){let a=Kr(t,e);return at({all(c,...f){return a.prepare(c).all(...f)}},n,r,o,i,s)}async function ln(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Vr,buildSearchIndex:(n,r,o)=>eo(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(no(e,i,r,o,s,a,c))}}import{readFile as ro,stat as oo,writeFile as io}from"fs/promises";var Qt=null,N=null;async function qt(){return Qt||(Qt=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),Qt}function so(t){return{all(e,...n){let r=t.prepare(e);n.length>0&&r.bind(n);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function ao(t){let e=await oo(t);if(N&&N.dbPath===t&&N.mtimeMs===e.mtimeMs)return N.db;N?.db.close();let n=await qt(),r=n.capi,o=n.wasm,i=new Uint8Array(await ro(t)),s=o.allocFromTypedArray(i),a=new n.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),N={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function dn(){N?.db.close(),N=null}async function co(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}t.exec("COMMIT")}function uo(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function lo(t,e,n){await v();let r=await qt(),o=new r.oo1.DB(":memory:","c");o.exec(ct);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=uo(o,i,s),f=e.length;for(let u=0;u<f;u+=B){let E=e.slice(u,u+B),g=await Promise.all(E.map(async A=>({source:A,searchText:await ot(A)})));await co(o,a,c,g),await n?.(Math.min(u+E.length,f),f)}o.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(o);await io(t,p),o.close(),dn()}async function mo(t,e,n,r,o,i){let s=await ao(t);return at(so(s),e,n,r,o,i)}async function mn(){return await qt(),{kind:"sqlite-wasm",resetCache:dn,buildSearchIndex:lo,searchIndex:(t,e,n,r,o,i,s)=>mo(r,e,n,o,i,s)}}var ut=null,Yt=null;async function fo(){try{let e=await ln();return it("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){it(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let t=await mn();return it("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),t}async function Vt(){return ut||(ut=fo().then(t=>(Yt=t,t))),ut}function fn(){Yt?.resetCache(),ut=null,Yt=null}function pn(){fn()}async function gn(t,e,n){await(await Vt()).buildSearchIndex(t,e,n)}import{unified as bn}from"unified";import Tn from"remark-parse";import In from"remark-gfm";import{toString as dt}from"mdast-util-to-string";var po=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,go=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,ho=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,So=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,yo=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function lt(t){let e=t.trim(),n=e.match(So);return n?n[1]:e}function xo(t){let e=t.match(po);if(!e)return;let n=lt(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function _o(t){let e=lt(t.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:t,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(t))return{displayTitle:t,symbolName:e,searchExtras:[e]}}function U(t){let e=t.trim();return e?xo(e)??(()=>{let n=e.match(go);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(ho);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??_o(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function Eo(t){if(t.length<2||t.length>36||yo.test(t))return!1;let e=[...t.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function hn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(Eo(n))return n}return""}function Sn(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var Ao=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,$=/@[A-Z][a-zA-Z]+/g,bo=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,To=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Io=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Do=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),wo=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),Co=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function Dn(t,e){let n=new Set,r=[t,...e];for(let o of r){for(let i of Ft(o)){T(n,i);let s=et(i);s&&T(n,s)}for(let i of vt(o))T(n,i);for(let i of o.matchAll(Ao)){let s=i[0];Ro(s)&&n.add(s)}for(let i of o.matchAll($))n.add(i[0])}return F([...n])}function Ro(t){let e=t.trim();if(!e||$.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return Co.has(n)?!1:/^[A-Z]/.test(n)}return Do.has(e)?!1:wo.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function yn(t){let e=t.trim();return!!(!e||Io.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function wn(t,e){let n=e.jsonTitle?.trim(),r=Po(t,"").trim(),o=e.fileName.trim();return n&&!yn(n)?n:r&&!yn(r)?r:n||r||o}function Cn(t){return bo.test(t.trim())}function Kt(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=lt(e);return To.test(n)}function mt(t){let e=t.trim();return e?$.test(e)||Cn(e)||Kt(e)?!0:!!U(e).symbolName:!1}function No(t){let e=t.trim();return!(!e||Cn(e)||Kt(e))}function Oo(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!No(o)||e.has(o)||(e.add(o),n.push(o))}return n}function xn(t){if(!t.includes("."))return 0;let e=t.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Lo(t,e){let n=xn(t)-xn(e);return n!==0?n:t.localeCompare(e)}function Rn(t,e=[]){let n=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(n),o=[...new Set(t.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(Lo),[...n,...o].slice(0,Se)}function ft(t){return t.replace(/\s+/g," ").trim()}function _n(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Po(t,e=""){let n=t.split(/\r?\n/),r=0;for(;r<n.length&&!n[r].trim();)r+=1;if(r>=n.length)return e;let o=_n(n[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return _n(i[1].trim());if(r+1<n.length){let s=n[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function Nn(t){let e=ft(t.join(" "));if(e.length<=W)return e;let n=e.slice(0,W);return e.length<=W+yt?n:`${n} ${e.slice(-yt)}`}function Bo(t){let e=Oo(t).join(" ");return e.length<=xt?e:e.slice(0,xt)}function On(t){let e=ft(t),{text:n,excerptTruncated:r}=sn(e,ye);return{leadText:n,excerptTruncated:r}}function Mo(t,e){let{leadText:n,excerptTruncated:r}=On(t);return{leadText:n,excerptTruncated:r||!!e.trim()}}function Ln(t,e){if(t.type==="code"){e.codeBlocks.push(t.value??"");return}if("children"in t&&Array.isArray(t.children)){for(let r of t.children)Ln(r,e);return}let n=ft(dt(t));n&&e.bodyParts.push(n)}function ko(t){let e=bn().use(Tn).use(In).parse(t),n=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&n.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=dt(a).trim();if(a.depth>=4&&c&&mt(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Ln(s,r)}return o(),n.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:n}function Fo(t){return ie.test(t)}function vo(t){return t.filter(e=>e.sectionTitle&&mt(e.sectionTitle)).length}function zo(t){return{sectionTitle:t.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:t.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:t.flatMap(e=>e.codeBlocks).slice(0,8)}}function En(t){let e=t.trim();return!e||$.test(e)?$.test(e):/对象说明$|枚举说明$/.test(e)?!0:Kt(e)}function Ho(t){let e=t.filter(u=>!u.sectionTitle||!mt(u.sectionTitle)),n=t.filter(u=>u.sectionTitle&&mt(u.sectionTitle)),r=n.filter(u=>En(u.sectionTitle)),o=n.filter(u=>!En(u.sectionTitle)),i=Math.max(0,oe-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(u=>An(u.sectionTitle)),f=a.filter(u=>!An(u.sectionTitle)),p=[];for(let u=0;u<f.length;u+=St)p.push(zo(f.slice(u,u+St)));return[...e,...r,...s,...c,...p]}function jo(t,e,n){let r=t.split(/\r?\n/).length,o=vo(e);return o===0?!1:Fo(n)?r>=ne&&o>=re:r>=te&&o>=ee}var Zo=/^\[h2\][A-Za-z]/;function An(t){return Zo.test(t.trim())}function Pn(t){if(!t.includes(" | ")){let n=U(t);return n.symbolName?[n.symbolName]:[]}let e=[];for(let n of t.split(" | ")){let r=U(n.trim()).symbolName;r&&e.push(r)}return e}function Uo(t,e,n,r){let o=Pn(t),i=Dn(n,r);return e.symbolName&&i.push(e.symbolName),Rn([...o,...i],o)}function $o(t,e){let n=Nn(t.bodyParts),r=t.sectionTitle.trim(),o=U(r),i=hn(t.bodyParts),s=Sn(r,i,o),a=Pn(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,f=[e.docTitle,s,...t.bodyParts].join(" "),{leadText:p,excerptTruncated:u}=Mo(n,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:Uo(r,o,f,t.codeBlocks),bodySample:n,leadText:p,excerptTruncated:u}}function Bn(t,e){for(let n of t){if(n.type==="heading"){let o=dt(n).trim();o&&e.headings.push(o);continue}if(n.type==="code"){e.codeBlocks.push(n.value??"");continue}if("children"in n&&Array.isArray(n.children)){Bn(n.children,e);continue}let r=ft(dt(n));r&&e.bodyParts.push(r)}}function Go(t){let e=bn().use(Tn).use(In).parse(t),n={headings:[],bodyParts:[],codeBlocks:[]};return Bn(e.children,n),n}function Xo(t,e){let n=Go(t),r=e.docTitle?.trim()||e.documentId,o=Nn(n.bodyParts),i=[r,...n.headings,o].join(" "),{leadText:s,excerptTruncated:a}=On(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:Bo(n.headings),apiSymbols:Rn(Dn(i,n.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Mn(t,e){let n=e.docTitle?.trim()||e.documentId,r=ko(t);return jo(t,r,e.documentId)?Ho(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>$o(o,{...e,docTitle:n})):[Xo(t,{...e,docTitle:n})]}async function Wo(t){let e=[];async function n(r){let o=await y.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}function Qo(t,e){let n=_.relative(e,t).split(_.sep).join("/").split("/");if(n[0]==="docs"&&(n=n.slice(1)),n.length<2)return null;let r=n[0],o=Ee[r];if(o===void 0)return null;let i=n[n.length-1].replace(/\.md$/,"");return n[n.length-1]=i,{documentId:n.join("/"),catalogId:o,docTitle:i}}async function qo(t){let e=t.replace(/\.md$/,".json");try{let n=await y.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Yo(t,e){let n=Qo(t,e);if(!n)return[];let r=await y.promises.readFile(t,"utf-8"),o=wn(r,{jsonTitle:await qo(t),fileName:n.docTitle});return Mn(r,{...n,docTitle:o})}async function Vo(t,e,n){let r=_.join(e,"search.db");return await gn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}async function Ko(t){let e=await Wo(t),n=[];for(let r of e){let o=await Yo(r,t);n.push(...o)}return n}function Jo(t,e){return{indexVersion:X,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function Fn(t){t.lexiconDir&&Dt(t.lexiconDir);try{let e=await Ko(t.docsDir);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await y.promises.mkdir(t.tmpDir,{recursive:!0});let n=await Vo(e,t.tmpDir,t.onProgress),r=Jo(t,n);return await y.promises.writeFile(_.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Oe(t.tmpDir),r}finally{t.lexiconDir&&Dt(null)}}async function vn(){return y.promises.mkdtemp(_.join(kn.tmpdir(),"deveco-docs-"))}async function ti(t,e){try{await y.promises.rename(t,e)}catch(n){let r=n.code;if(r!=="EPERM"&&r!=="EXDEV")throw n;await y.promises.cp(t,e,{recursive:!0}),await y.promises.rm(t,{recursive:!0,force:!0})}}async function zn(t){let e=_.join(t,"docs");try{await y.promises.access(e)}catch{return}let n=new Set(["docs","docs.zip"]);for(let r of await y.promises.readdir(e,{withFileTypes:!0})){if(n.has(r.name))continue;let o=_.join(e,r.name),i=_.join(t,r.name);await y.promises.rm(i,{recursive:!0,force:!0}),await ti(o,i)}await y.promises.rm(_.join(e,"docs"),{recursive:!0,force:!0}),await y.promises.rm(_.join(e,"docs.zip"),{force:!0}),await y.promises.rm(e,{recursive:!0,force:!0})}async function oi(t){let e=At();await h.promises.mkdir(H.dirname(e),{recursive:!0}),await h.promises.appendFile(e,`${new Date().toISOString()} ${t}
65
- `)}async function ii(t){let e=O();if(!e)throw new Error("docs.zip not found");await h.promises.rm(t,{recursive:!0,force:!0}),await h.promises.mkdir(t,{recursive:!0}),new ei(e).extractAllTo(t,!0),await zn(t)}async function si(){let t=x(),e=M(),n=await h.promises.readdir(e);for(let r of n){let o=H.join(t,r);await h.promises.rm(o,{force:!0}),await h.promises.rename(H.join(e,r),o)}await h.promises.rm(e,{recursive:!0,force:!0}),await h.promises.rm(H.join(t,"orama.dpack"),{force:!0})}async function ai(t,e){e?.start("Installing documentation index\u2026"),await R({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Be(t),e&&(e.text="Documentation index installed.")}async function ci(t,e,n){let r=M(),o=await vn();await h.promises.mkdir(x(),{recursive:!0}),await h.promises.rm(r,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await R({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ii(o),await Fn({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:tt(),synonymsHash:J(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await R({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await h.promises.rm(o,{recursive:!0,force:!0})}await R({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await si(),pn()}async function Hn(t){await R({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function ui(t){let e=await Lt(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await R({state:"done",message:n,error:null})}async function li(t,e){let n=t instanceof Error?t.message:String(t);throw await R({state:"error",error:n}),await oi(`ERROR: ${n}`),e?.fail(n),t}async function di(){let t=x();await h.promises.mkdir(t,{recursive:!0});let e=Ie();return h.existsSync(e)||await h.promises.writeFile(e,"","utf-8"),e}async function mi(){let t=await di();return ni.lock(t,{stale:1800*1e3})}async function fi(){let t=O(),e=(t?await K(t):null)??await Ot();if(!e)throw new Error("docs.zip not found");return e}async function pi(t,e){let n=await fi(),r=t.force||await je(t.force),o=await Pt(t.force);if(!r&&!o&&Bt()){await ui(e);return}if(Rt()&&!t.force){await ai(n,e),await Hn(e);return}await ci(t,n,e),await Hn(e)}var pt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:ri({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await mi(),await Nt(He("Starting documentation setup\u2026")),await pi(e,o)}catch(s){return li(s,o)}finally{i&&await i()}}};var gi=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";pt.run({background:!0,builtBy:gi}).catch(()=>{process.exit(1)});
65
+ `)}async function ii(t){let e=O();if(!e)throw new Error("docs.zip not found");await h.promises.rm(t,{recursive:!0,force:!0}),await h.promises.mkdir(t,{recursive:!0}),new ei(e).extractAllTo(t,!0),await zn(t)}async function si(){let t=x(),e=M(),n=await h.promises.readdir(e);for(let r of n){let o=H.join(t,r);await h.promises.rm(o,{force:!0}),await h.promises.rename(H.join(e,r),o)}await h.promises.rm(e,{recursive:!0,force:!0}),await h.promises.rm(H.join(t,"orama.dpack"),{force:!0})}async function ai(t,e){e?.start("Installing documentation index\u2026"),await R({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Be(t),e&&(e.text="Documentation index installed.")}async function ci(t,e,n){let r=M(),o=await vn();await h.promises.mkdir(x(),{recursive:!0}),await h.promises.rm(r,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await R({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ii(o),await Fn({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:tt(),synonymsHash:J(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await R({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await h.promises.rm(o,{recursive:!0,force:!0})}await R({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await si(),pn()}async function Hn(t){await R({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function ui(t){let e=await Lt(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await R({state:"done",message:n,error:null})}async function li(t,e){let n=t instanceof Error?t.message:String(t);throw await R({state:"error",error:n}),await oi(`ERROR: ${n}`),e?.fail(n),t}async function di(){let t=x();await h.promises.mkdir(t,{recursive:!0});let e=Ie();return h.existsSync(e)||await h.promises.writeFile(e,"","utf-8"),e}async function mi(){let t=await di();return ni.lock(t,{stale:1800*1e3})}async function fi(){let t=O(),e=(t?await K(t):null)??await Ot();if(!e)throw new Error("docs.zip not found");return e}async function pi(t,e){let n=await fi(),r=t.force||await je(t.force),o=await Pt(t.force);if(!r&&!o&&Bt()){await ui(e);return}if(Rt()&&!t.force){await ai(n,e),await Hn(e);return}await ci(t,n,e),await Hn(e)}var pt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:ri({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await mi(),await Nt(He("Starting documentation setup\u2026")),await pi(e,o)}catch(s){await li(s,o)}finally{i&&await i()}}};var gi=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";pt.run({background:!0,builtBy:gi}).catch(()=>{process.exit(1)});
package/index.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/hmos-deveco-cli",
3
- "version": "0.1.0-TD.5",
3
+ "version": "0.1.0-TD.5.1-alpha1",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "license": "MIT",
6
6
  "type": "module",