@deveco-test/deveco-cli 1.3.0-Test.3 → 1.3.0-Test.5

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
@@ -30,7 +30,7 @@ Available runnable modules:
30
30
  `))}async function yp(n,e,t,r,i,o){o&&(console.log(`Uninstalling ${t}...`),await n.uninstallApp(e,t)||console.log(`App ${t} not installed; skipping uninstallation.`)),console.log(`
31
31
  Installing artifacts to device ${e}...`),await n.installApp(e,r),console.log(`Launching ${t}/${i}...`);let s=await n.launchApp(e,t,i);console.log(Ys(`
32
32
  Application '${t}': ${s}`))}var vp=new up("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").action(async n=>{try{await bp(n)}catch(e){console.error(pp(e.message)),process.exit(1)}});async function wp(n,e,t,r,i){let o=new ft(e,n.rootDir),s=new nt(e,n.rootDir),a=new Set;for(let{moduleName:f,targetName:P}of t)for(let C of n.collectNonHarDependentModuleList(f))a.add(`${C}@${P}`);let c=[...a],l=Hi(n,c),u={type:"modules",modulesToBuild:c,moduleTasks:l};await Kt(n.rootDir,()=>Fi(o,s,r,i,u,n.rootDir),()=>console.log("Another build is already running for this project. Waiting for completion...")),console.log(`
33
- `+Ys("Build completed successfully."))}async function bp(n){let e=tt.discover(process.cwd());console.warn(mp("Ensure the project source is trusted before proceeding."));let t=await N.new(),i=gp(e,n.module).map(hp);for(let{moduleName:ne}of i){let he=e.getModuleType(ne);if(he!=="entry"&&he!=="feature"&&he!=="shared")throw new Error(`Module '${ne}' '${he}' is not runnable. Specify an entry or feature module.`)}let o=new Kn(t),s=G.from(t),a=await fp(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 wp(e,t,i,l,u);let f=new Set;for(let{moduleName:ne,targetName:he}of i){let Wn=e.collectNonHarDependentModuleList(ne);for(let Lu of Wn)f.add(e.findArtifactPath(Lu,he,c,l));f.add(e.findArtifactPath(ne,he,c,l))}let P=[...f],C=e.getBundleName(),L=e.getMainAbility(i[0].moduleName,n.ability);await yp(o,a,C,P,L,!!n.uninstall)}var Js=vp;import{Command as Sp}from"commander";import{green as Ks,red as Zs,cyan as Bi}from"colorette";import{execa as Xs}from"execa";function Ep(){return"@deveco-test/deveco-cli"}function Pp(){return"1.3.0-Test.3"}var Cp=new Sp("update").description("Update deveco-cli to latest").action(async()=>{let n=Ep(),e=Pp();console.log(Bi("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
33
+ `+Ys("Build completed successfully."))}async function bp(n){let e=tt.discover(process.cwd());console.warn(mp("Ensure the project source is trusted before proceeding."));let t=await N.new(),i=gp(e,n.module).map(hp);for(let{moduleName:ne}of i){let he=e.getModuleType(ne);if(he!=="entry"&&he!=="feature"&&he!=="shared")throw new Error(`Module '${ne}' '${he}' is not runnable. Specify an entry or feature module.`)}let o=new Kn(t),s=G.from(t),a=await fp(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 wp(e,t,i,l,u);let f=new Set;for(let{moduleName:ne,targetName:he}of i){let Wn=e.collectNonHarDependentModuleList(ne);for(let Lu of Wn)f.add(e.findArtifactPath(Lu,he,c,l));f.add(e.findArtifactPath(ne,he,c,l))}let P=[...f],C=e.getBundleName(),L=e.getMainAbility(i[0].moduleName,n.ability);await yp(o,a,C,P,L,!!n.uninstall)}var Js=vp;import{Command as Sp}from"commander";import{green as Ks,red as Zs,cyan as Bi}from"colorette";import{execa as Xs}from"execa";function Ep(){return"@deveco-test/deveco-cli"}function Pp(){return"1.3.0-Test.5"}var Cp=new Sp("update").description("Update deveco-cli to latest").action(async()=>{let n=Ep(),e=Pp();console.log(Bi("Checking for updates..."));try{let{stdout:t}=await Xs("npm",["view",n,"version"]),r=t.trim();if(r===e){console.log(Ks(`
34
34
  ${n} is already up to date (version ${e}.)`));return}console.log(Bi(`
35
35
  New version found: ${r} (current: ${e})`)),console.log(Bi(`Updating ${n}...`)),await Xs("npm",["install","-g",`${n}@latest`],{stdio:"inherit"}),console.log(`
36
36
  `+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=Cp;import{Command as Kp}from"commander";import{execa as Xn}from"execa";function V(n){return n.normalize("NFKC").replace(/\s+/g," ").trim()}import{spawn as Dp}from"child_process";var Ip=2500;function Ap(n,e,t,r,i,o){n.once("exit",s=>{if(o())return;clearTimeout(e);let a=t();s===0||s===null?r():i(a||`Emulator process exited with code ${s}`)})}function xp(n,e,t,r){let i=!1,o=()=>i,s=()=>Buffer.concat(e).toString("utf8").trim(),a=()=>{i||(i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners(),n.stderr?.destroy(),n.unref(),t())},c=u=>{if(!i){i=!0,clearTimeout(l),n.removeAllListeners(),n.stderr?.removeAllListeners();try{n.kill()}catch{}r(new Error(u))}},l=setTimeout(a,Ip);n.once("error",u=>c(u.message)),Ap(n,l,s,a,c,o)}function ea(n,e,t){return g(`Spawning emulator: ${n} ${t.join(" ")}`),new Promise((r,i)=>{let o=[],s=Dp(n,t,{detached:!0,stdio:["ignore","ignore","pipe"],env:{...process.env,DEVECO_SDK_HOME:e},windowsHide:!0});s.stderr?.on("data",a=>o.push(a)),xp(s,o,r,i)})}import*as vt from"path";function Tp(n){let e=new Set,t=[];for(let r of n){let i=JSON.stringify(r);e.has(i)||(e.add(i),t.push(r))}return t}function kp(n){let e=n.instancePath?.trim();if(e)return vt.dirname(vt.normalize(e)).replace(/\\/g,"/");let t=n.path?.trim();return t?vt.dirname(vt.normalize(t)).replace(/\\/g,"/"):""}function Rp(n){let e=[];return n&&e.push(["-imageRoot",n]),e.push([]),e}function ta(n,e){return e?[...n,"-bootmode",e]:n}function Mp(n,e,t){let r=[ta(["-start",n],t)],i=kp(e);if(i)for(let o of Rp(e.imageRoot))r.push(ta(["-hvd",n,"-path",i,...o],t));return Tp(r)}async function na(n,e,t,r){let i=new Error("No start strategy ran"),o=Mp(n,e,r);for(let s of o)try{return await t(s),{ok:!0}}catch(a){i=a}return{ok:!1,lastError:i}}async function Wi(n){return(await G.withHdcPath(n).listDevices()).map(t=>t.serial).filter(Xt)}async function Ui(n){let e=await Wi(n);return e.length===0?[]:(await Promise.all(e.map(r=>Jn(n,r,"ohos.qemu.hvd.name")))).filter(r=>!!r)}async function ra(n,e){return(await Ui(n)).includes(e)}import*as bt from"path";import{existsSync as Op,statSync as Lp}from"fs";function wt(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function Np(n){let e=wt(n,["instancePath","instance_path","InstancePath","instancepath","instanceDir","instance_dir","InstanceDir","deployPath","deploy_path","deployedPath","deployed_path","workPath","work_path","dataPath","data_path"]);if(e)return e;for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let i=t.toLowerCase();if(i.includes("instance")&&(i.includes("path")||i.includes("dir"))||i==="deployedpath")return r.trim()}return""}function _p(n){return wt(n,["uuid","UUID","Uuid","instanceUuid","instance_uuid","InstanceUuid"])}function Hp(n){let e=n.find(r=>r.instancePath?.trim());if(!e?.instancePath?.trim())return;let t=bt.dirname(bt.normalize(e.instancePath));for(let r of n){if(r.instancePath?.trim())continue;let i=bt.join(t,r.name);Op(i)&&Lp(i).isDirectory()&&(r.instancePath=i.replace(/\\/g,"/"))}}function Fp(n){try{let e=JSON.parse(n);return Array.isArray(e)?e.map(t=>{let r=_p(t),i=wt(t,["deviceType","DeviceType","devicetype"]),o=wt(t,["os.osVersion","osVersion","OsVersion","OSVersion"]);return{name:t.name||t.Name||"",isRunning:t.isRunning===!0||String(t.isRunning).toLowerCase()==="true",instancePath:Np(t),path:wt(t,["path","Path","hvdPath","hvd_path"]),imageRoot:wt(t,["imageRoot","image_root","ImageRoot"]),uuid:r||void 0,deviceType:i||void 0,osVersion:o||void 0}}).filter(t=>t.name):null}catch{return null}}function jp(n){let e=[],t=/^(name|isrunning|instancepath|path|imageroot|devicetype|os\.osversion)\s*:\s*(.+)/gim,r=null,i;for(;(i=t.exec(n))!==null;){let[,o,s]=i;if(o.toLowerCase()==="name")r&&e.push(r),r={name:s.trim()};else if(r){let a=o.toLowerCase();a==="isrunning"?r.isRunning=s.trim().toLowerCase()==="true":a==="instancepath"?r.instancePath=s.trim():a==="path"?r.path=s.trim():a==="imageroot"?r.imageRoot=s.trim():a==="devicetype"?r.deviceType=s.trim():a==="os.osversion"&&(r.osVersion=s.trim())}}return r&&e.push(r),e}function ia(n){let t=Fp(n)??jp(n);return Hp(t),t}function zi(n,e){for(let t of e){let r=n[t];if(typeof r=="string"&&r.trim())return r.trim()}return""}function $p(n){let e=n.downloaded??n.Downloaded;return e===!0||String(e).toLowerCase()==="true"}function Bp(n){if(!$p(n))return null;let e=zi(n,["osVersion","OsVersion","OSVersion"]),t=zi(n,["SoftWareVersion","SoftwareVersion","softwareVersion"]),r=zi(n,["deviceType","DeviceType"]);return!e&&!t?null:{osVersion:e,softwareVersion:t,deviceType:r}}function Zn(n){let e=n.trim();if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))return[];let r=[];for(let i of t){if(!i||typeof i!="object")continue;let o=Bp(i);o&&r.push(o)}return r}catch{return[]}}function oa(n){let t=Zn(n).map(r=>r.osVersion).filter(Boolean);return[...new Set(t)]}var sa=/no images are available/i,Wp="7.0.0";function De(n){return n.normalize("NFKC").trim().toLowerCase()}function Up(n){let e=n.message||"";return sa.test(e)}function zp(n){return n.normalize("NFKC").match(/(\d+(?:\.\d+){1,3})/)?.[1]}function qp(n,e){let t=n.split(".").map(o=>Number(o)),r=e.split(".").map(o=>Number(o)),i=Math.max(t.length,r.length);for(let o=0;o<i;o++){let s=(t[o]??0)-(r[o]??0);if(s!==0)return s}return 0}function Qt(n,e){return`${n} ${e.join(" ")}`.trim()}function Gp(n){switch(n.type){case"gps":return`${n.type}:${n.key}=${n.value}`;case"sensor":return`${n.type}:${n.key}=${n.value}`;case"rotation":case"volume":return`${n.type}:${n.direction}`;case"folded-state":return`${n.type}:${n.state}`;case"battery":return`${n.type}:${n.level}`;case"battery-status":return`${n.type}:${n.status}`;default:return n.type}}var St=class n{static supportedControlPaths=new Set;emulatorPath;sdkPath;hdcPath;constructor(e,t,r){this.emulatorPath=e,this.sdkPath=t,this.hdcPath=r}static from(e){return new n(e.emulatorPath,e.sdkPath,e.hdcPath)}async executeEmulator(e){return g(`Executing: ${Qt(this.emulatorPath,e)}`),Xn(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 ia(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),i=t.find(a=>V(a.name)===r);if(!i)throw new Error(`Emulator "${e}" not found.`);let o=i.name;if(await this.isAlreadyRunning(o,i))return"already-running";await this.assertSystemImageAvailable(i);let s=await na(o,i,a=>this.executeEmulatorDetached(a),"snapshot");if(s.ok)return"started";if(await this.isAlreadyRunning(o))return"already-running";throw new Error(`Unable to start emulator "${e}". All methods failed.
@@ -1277,7 +1277,7 @@ Output so far:
1277
1277
  `).length,o=await this.withOpenFile(t,async a=>this.manager.sendFeatureRequest(y.INLAY_HINT,{textDocument:{uri:a},range:{start:{line:0,character:0},end:{line:i,character:0}}}));return{content:[{type:"text",text:o==null?"inlayHint: no result":`inlayHint: ${JSON.stringify(o,null,2)}`}]}}catch(r){return this.buildErrorResponse("inlayHint",r)}}async handleDocumentLink(e){if(!this.initialized)return this.buildNotReadyResponse();let t=this.resolveSingleFile(e);if(!t)return{content:[{type:"text",text:`\u6587\u4EF6\u4E0D\u5B58\u5728\u6216\u4E0D\u662F .ets \u6587\u4EF6: ${e}`}],isError:!0};try{let r=await this.withOpenFile(t,async o=>this.manager.sendFeatureRequest(y.DOCUMENT_LINK,{textDocument:{uri:o}}));return{content:[{type:"text",text:r==null?"documentLink: no result":`documentLink: ${JSON.stringify(r,null,2)}`}]}}catch(r){return this.buildErrorResponse("documentLink",r)}}buildErrorResponse(e,t){let r=t instanceof Error?t.message:String(t);return h.error(`${e} failed: ${r}`),{content:[{type:"text",text:`${e} failed: ${r}`}],isError:!0}}async withOpenFile(e,t){let r=at(e),i=await re.promises.readFile(e,"utf8"),s=`deveco.apptool.${Y.extname(e).replace(/^\./,"")||"plaintext"}`;h.debug(`withOpenFile didOpen uri=${r} len=${i.length}`),this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,text:i,languageId:s,version:i.length}});try{return await t(r)}finally{this.sendNotification("textDocument/didClose",{textDocument:{uri:r},isManual:!1})}}resolveSingleFile(e){let t=Y.isAbsolute(e)?e:Y.join(this.projectPath,e);return!re.existsSync(t)||!re.statSync(t).isFile()||!t.endsWith(".ets")?null:t}buildNotReadyResponse(){return{content:[{type:"text",text:this.initializing?"LSP \u6B63\u5728\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5":this.projectPath?"LSP\u672A\u521D\u59CB\u5316":"\u6CA1\u6709\u914D\u7F6E\u5DE5\u7A0B\u8DEF\u5F84\uFF0C\u8BF7\u914D\u7F6EPROJECT_PATH\u53C2\u6570"}],isError:!0}}collectValidFiles(e,t){let r=this.projectPath,i=[];for(let o of e){let s=Y.isAbsolute(o)?o:Y.join(r,o);if(!re.existsSync(s)){t.push(`\u6587\u4EF6\u4E0D\u5B58\u5728: ${o}`);continue}if(!re.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,r){for(let i of e){await zc(500);try{let o=await this.checkFile(i);r.push(qg(i,o))}catch(o){t.push(`${i} => wait for diagnostics failed: ${o.message}`)}}}formatCallResult(e,t){let r=[];e.length>0&&r.push(e.join(`
1278
1278
  `)),t.length>0&&r.push(t.join(`
1279
1279
  `));let i=r.join(`
1280
- `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(We),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Y.join(At(),"ArkTSCheck"),r=Y.join(t,"mapping-config.properties"),i=Gc(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Y.join(t,"lsp-log",String(i),o),a=Y.join(t,"lsp-index",String(i));return re.mkdirSync(s,{recursive:!0}),re.mkdirSync(a,{recursive:!0}),{logPath:ue(s),indexPath:ue(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function zg(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function qg(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 Gg}from"child_process";import*as M from"fs";import*as B from"path";import{z as No}from"zod";var vl=60*1e3,Vg=30*1e3,Yg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Jg=1e3,_o=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=>{h.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=ue(this.projectPath),i=at(r),o=B.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.3"},rootPath:r,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,vl),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,h.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=vl,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=M.realpathSync(e)}catch{t=e}let r=at(t),i=qc(t),o=await M.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}`))},Vg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:i,version:1,text:o}})}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=>{h.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){h.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){h.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){h.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}Yg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){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`))},r);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,r)=>{let i;try{i=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1280
+ `).trim(),o=e.length>0;return!o&&t.length===0&&(i="\u672A\u6536\u96C6\u5230\u8BCA\u65AD\u4FE1\u606F"),{content:[{type:"text",text:i}],isError:o}}async shutdown(){let e=this.initReject;if(this.clearInitHandlers(),e?.(new Error("LSP shutting down")),this.manager){try{await this.manager.dispose()}catch(t){h.warn(`Failed to dispose ArktsLspManager: ${t}`)}this.manager=null}this.initialized=!1,this.initializing=!1,this.initPromise=null}sendNotification(e,t){if(!this.manager)throw new Error("ArktsLspManager not initialized");this.manager.sendNotification({jsonrpc:"2.0",method:e,params:t})}handleLspMessage(e){let t=e,r=t.method;if(r)switch(r){case"textDocument/publishDiagnostics":{this.handleDiagnosticsNotification(t.params);break}case"arkts/indexingProgress":this.initResolve&&(this.armInitTimer(We),h.debug("Received arkts/indexingProgress, reset init timeout"));break;case"arkts/initialized":{h.info("Received arkts/initialized");let i=this.initResolve;this.clearInitHandlers(),i?.();break}case"arkts/initializationFailed":{let o=t.params?.message??"unknown";h.error(`LSP initialization failed: ${o}`);let s=this.initReject;this.clearInitHandlers(),s?.(new Error(`LSP initialize failed: ${o}`));break}case"workspace/didChangeConfiguration":h.info("Received workspace/didChangeConfiguration, sync deferred to next check");break;default:break}}handleDiagnosticsNotification(e){if(!e)return;let t=e.uri;if(!t)return;let r=this.popDiagnosticWaiter(t);if(!r&&this.diagnosticWaiters.size===1){let s=this.diagnosticWaiters.keys().next().value;r=this.popDiagnosticWaiter(s)}if(!r)return;if(typeof e.errorMessage=="string"){h.warn(`diagnostics error uri=${t} message=${e.errorMessage}`),r.resolve({errorMessage:e.errorMessage});return}let i=e.diagnostics,o=Array.isArray(i)?i.length:0;h.debug(`diagnostics received uri=${t} count=${o}`),r.resolve(Array.isArray(i)?i:[])}popDiagnosticWaiter(e){let t=this.diagnosticWaiters.get(e);if(t)return this.diagnosticWaiters.delete(e),clearTimeout(t.timer),t}getLogAndIndexPath(e){try{let t=Y.join(At(),"ArkTSCheck"),r=Y.join(t,"mapping-config.properties"),i=Gc(e,r),o=`${Date.now()}${process.hrtime.bigint()%1000000n}`,s=Y.join(t,"lsp-log",String(i),o),a=Y.join(t,"lsp-index",String(i));return re.mkdirSync(s,{recursive:!0}),re.mkdirSync(a,{recursive:!0}),{logPath:ue(s),indexPath:ue(a)}}catch{return{logPath:"auto",indexPath:"auto"}}}};function zg(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;if(e.kind==="full"&&Array.isArray(e.items))return e.items}return[]}function qg(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 Gg}from"child_process";import*as M from"fs";import*as B from"path";import{z as No}from"zod";var vl=60*1e3,Vg=30*1e3,Yg=new Set(["textDocument/didOpen","textDocument/didChange","textDocument/didClose","textDocument/didSave"]),Jg=1e3,_o=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=>{h.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=ue(this.projectPath),i=at(r),o=B.basename(r)||"workspace",s={processId:null,clientInfo:{name:"devecocli-mcp-server",version:"1.3.0-Test.5"},rootPath:r,rootUri:i,workspaceFolders:[{uri:i,name:o}],capabilities:{}};await this.sendRequestToClangd("initialize",s,vl),await this.sendNotificationToClangd("initialized",{}),this.backendReady=!0,this.wrapperState="proxying";for(let a of this.queuedDocumentNotifications)await this.writeToClangd(a);this.queuedDocumentNotifications.length=0,h.info("[CppCheck] clangd backend ready, switched to proxying mode")}async waitForBackendReady(){if(this.backendReady)return;let e=vl,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=M.realpathSync(e)}catch{t=e}let r=at(t),i=qc(t),o=await M.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}`))},Vg);this.diagnosticWaiters.set(r,{resolve:a,reject:c,timer:l})});try{await this.sendNotification("textDocument/didOpen",{textDocument:{uri:r,languageId:i,version:1,text:o}})}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=>{h.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){h.warn(`[CppCheck] shutdown request failed: ${e}`)}try{await this.sendNotificationToClangd("exit",null)}catch(e){h.warn(`[CppCheck] exit notification failed: ${e}`)}try{this.clangdStdin.end()}catch(e){h.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}Yg.has(e)&&this.queuedDocumentNotifications.push(r)}async closeFile(e){await this.sendNotification("textDocument/didClose",{textDocument:{uri:e}})}async sendRequestToClangd(e,t,r){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`))},r);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,r)=>{let i;try{i=JSON.stringify(e)}catch(u){r(new Error(`Failed to encode LSP message: ${u}`));return}let o=Buffer.from(i,"utf8"),s=Buffer.from(`Content-Length: ${o.length}\r
1281
1281
  \r
1282
1282
  `,"ascii"),a=!1,c=u=>{a||(a=!0,u?r(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
1283
1283
  \r
@@ -1292,7 +1292,7 @@ Output so far:
1292
1292
  `),a.join(`
1293
1293
  `)].filter(f=>f.trim().length>0).join(`
1294
1294
  `).trim()||"No diagnostics collected"}],isError:l}}async callArktsCheck(e){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS check rejected: project is ${Fo[this.projectState]}, files: ${e.join(", ")}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS check rejected: LSP is initializing, files: ${e.join(", ")}`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return this.arktsCheckTool.handleCall({files:e})}}async handleLspFeatureCall(e,t){let r=t.file,i=t.line,o=t.character;if(typeof r!="string"||typeof i!="number"||typeof o!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let s=this.validateContainment([r]);return s||this.callArktsFeature(e,{file:r,line:i,character:o})}async handleWorkspaceSymbolCall(e){let t=e.query;return typeof t!="string"||t.trim().length===0?{content:[{type:"text",text:"Missing or invalid parameter: query (non-empty string required)."}],isError:!0}:this.callArktsWorkspaceSymbol(t)}async handleDocumentSymbolCall(e){let t=e.file;if(typeof t!="string")return{content:[{type:"text",text:"Missing or invalid parameter: file (string required)."}],isError:!0};let r=this.validateContainment([t]);return r||this.routeArktsRequest("documentSymbol",()=>this.arktsCheckTool.handleDocumentSymbol(t))}async handleCallHierarchyCall(e){let t=e.file,r=e.line,i=e.character,o=e.direction;if(typeof t!="string"||typeof r!="number"||typeof i!="number")return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="incoming"&&o!=="outgoing")return{content:[{type:"text",text:'Parameter direction must be "incoming" or "outgoing".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`callHierarchy(${o})`,()=>this.arktsCheckTool.handleCallHierarchy({file:t,line:r,character:i,direction:o}))}async handleCodeActionCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e);if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};let o=this.validateContainment([t]);return o||this.routeArktsRequest("codeAction",()=>this.arktsCheckTool.handleCodeAction({file:t,line:r,character:i}))}async handleRenameCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.newName;if(!t||typeof o!="string"||o.trim().length===0)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number), newName (non-empty string)."}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest("rename",()=>this.arktsCheckTool.handleRename({file:t,line:r,character:i,newName:o}))}async handleTypeHierarchyCall(e){let{file:t,line:r,character:i}=this.extractPositionArgs(e),o=e.direction;if(!t)return{content:[{type:"text",text:"Missing or invalid parameters. Required: file (string), line (number), character (number)."}],isError:!0};if(o!=="supertypes"&&o!=="subtypes")return{content:[{type:"text",text:'Parameter direction must be "supertypes" or "subtypes".'}],isError:!0};let s=this.validateContainment([t]);return s||this.routeArktsRequest(`typeHierarchy(${o})`,()=>this.arktsCheckTool.handleTypeHierarchy({file:t,line:r,character:i,direction:o}))}async handleCompletionItemResolveCall(e){let t=e.item;return t==null?{content:[{type:"text",text:"Missing parameter: item (completion item object required)."}],isError:!0}:this.routeArktsRequest("completionItemResolve",()=>this.arktsCheckTool.handleCompletionItemResolve(t))}extractPositionArgs(e){let t=e.file,r=e.line,i=e.character;return typeof t!="string"||typeof r!="number"||typeof i!="number"?{file:null,line:0,character:0}:{file:t,line:r,character:i}}async callArktsFeature(e,t){return this.routeArktsRequest(e,()=>this.arktsCheckTool.handleLspFeature(e,t))}async callArktsWorkspaceSymbol(e){return this.routeArktsRequest("workspaceSymbol",()=>this.arktsCheckTool.handleWorkspaceSymbol(e))}async routeArktsRequest(e,t){switch(this.projectState){case 0:return this.handleIdleCheck();case 1:case 2:return h.warn(`ArkTS ${e} rejected: project is ${Fo[this.projectState]}`),{content:[{type:"text",text:"Project is syncing, please retry in 10 seconds"}],isError:!0};case 3:return h.warn(`ArkTS ${e} rejected: LSP is initializing`),{content:[{type:"text",text:"ArkTS LSP is initializing, please retry in 10 seconds"}],isError:!0};case 5:return this.handleErrorCheck();case 4:return t()}}async handleIdleCheck(){if(this.ensureProjectReady(),this.config.projectPath){let e,t;return this.syncSkippedDueToLock?(e=`Another build process is running, sync deferred (waiting ${this.syncSkipStartedAt>0?Math.round((Date.now()-this.syncSkipStartedAt)/1e3):0}s), please retry in 25 seconds`,t="lock contention",this.syncSkippedDueToLock=!1):this.configChangedTriggeredResync?(e="Config file changed, resyncing project, please retry in 10 seconds",t="config changed",this.configChangedTriggeredResync=!1):(e="HarmonyOS project detected, syncing, please retry in 10 seconds",t="initial"),h.info(`Idle check: project '${this.config.projectPath}' already known, triggering init (${t})`),{content:[{type:"text",text:e}],isError:!0}}return this.workspaceRoot||this.originalProjectPath?(h.info(`Idle check: no project path yet, will try from '${this.workspaceRoot}' or '${this.originalProjectPath}'`),{content:[{type:"text",text:"Initializing, please retry in 10 seconds"}],isError:!0}):(h.warn("Idle check: no search candidates available"),{content:[{type:"text",text:"No HarmonyOS project detected. Please verify the project directory or create a project first."}],isError:!0})}async handleErrorCheck(){return this.initRetryCount>=Ho?(h.error(`Init retry limit reached (${this.initRetryCount}/${Ho}), will not auto-retry`),{content:[{type:"text",text:"Project initialization failed multiple times. Please check project configuration and restart the MCP Server."}],isError:!0}):(h.info(`Error check: auto-retrying (${this.initRetryCount}/${Ho})`),this.ensureProjectReady(),{content:[{type:"text",text:"Project initialization failed, auto-retrying, please retry in 10 seconds"}],isError:!0})}async callCppCheck(e){if(!this.cppCheckTool){let t=this.config.projectPath?"C++ LSP is not ready, please retry later":"Project path is not configured. Set the PROJECT_PATH parameter or open a project in DevEco Studio.";return h.warn(`C++ check rejected: ${t}, files: ${e.join(", ")}`),{content:[{type:"text",text:t}],isError:!0}}return this.cppCheckTool.handleCall({files:e})}mergeCheckResult(e,t,r){let i=e.content.map(o=>o.text).filter(o=>o&&o.trim().length>0).join(`
1295
- `);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new ly;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Kc();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Re(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){h.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Bt(e,this.config.devecoPath??null),h.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Re(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Re(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new $t(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=El(e);return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e)):(h.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,h.info("Starting project sync...");let t=await jt.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let r=Date.now()-this.syncSkipStartedAt,i=Math.round(r/1e3);return r>=Pl?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Pl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=fr(this.config.devecoPath??""),t=de(e);return ut.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Jc(),Yc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function dy(n){let e=[],t=[],r=[];for(let i of n)ut.extname(i).toLowerCase()===".ets"?e.push(i):gr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function jo(n={}){return new Qr(n)}import*as $o from"fs";import*as Wt from"path";import{spawn as uy}from"child_process";async function Dl(n){fn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await py(n),s=gy(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),vy(s)}async function py(n){let e=await my();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t=ue(n.projectPath??process.cwd()),r=Wt.join(de(e),"sdk"),i=It(e);i||(h.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=Wt.resolve(i,"ace-server","out","standardIndex","index.js"),s=Wt.join(At(),"lsp-server",String(Date.now()));$o.mkdirSync(s,{recursive:!0});let a=hy(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function my(){return N.new().then(n=>n.devecoStudioPath).catch(()=>be())}function hy(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=fy(n,e),s=Sr(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function fy(n,e){try{let t=[];return new dt(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Oe(n).getAllModuleInfo().length}catch{return 0}}function gy(n,e,t,r,i){let o=Wt.join(e,"lspLog");$o.mkdirSync(o,{recursive:!0});let s=yy(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),uy(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function yy(n,e,t,r,i){let o=j(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${j(t)}`,`--sdkPath=${j(r)}`]}function vy(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}async function by(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await N.new(),o=n,s=e??i.devecoStudioPath,a=jo({projectPath:o,devecoPath:s,nodeMaxOldSpaceSize:t,debug:r}),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(l){console.error("Failed to start MCP server:",l),process.exit(1)}}var Bo=new wy("serve").description("Host bundled auxiliary protocol servers");Bo.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await by()});Bo.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--project-path <path>","HarmonyOS project root path",process.cwd()).action(async n=>{n.arkts||(console.error("Use --arkts to start the ArkTS language server."),process.exit(1)),await Dl({projectPath:n.projectPath})});var Il=Bo;import{Command as wb,InvalidArgumentError as As}from"commander";import{red as xi,dim as bb}from"colorette";import*as z from"fs";import*as Jt from"path";import rb from"adm-zip";import ib from"proper-lockfile";import Ru from"ora";import*as Ee from"fs";import*as Tn from"path";var Ve=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],pt={"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 ei="1.9.1",fR=48*1024*1024,Al=280,xl=6,Tl=100,kl=3,Rl=28,Wo=10,Ml=/API参考|APIReference/i,In=200,Ol=12,Ll=4,Uo=8,Nl=6,ti=700,zo=250,qo=400,_l=1320,Hl=120,Fl=450,jl=250,$l=500,Bl=480,Wl=80,Ul=200,zl=60,ql=200,Gl=40,Vl=200,Yl=200,Jl=40,Ut=500,Kl=Object.fromEntries(Ve.map((n,e)=>[pt[n],e])),Ye=Object.fromEntries(Ve.map((n,e)=>[n,e]));import*as Ql from"fs";import*as O from"path";import{fileURLToPath as ed}from"url";import*as ni from"path";import{homedir as Sy}from"os";var Ey="deveco-cli";function Xl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Py(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Xl(n)!==""}function Zl(){return ni.join(Sy(),".local","share",Ey)}function ri(n){let e=ii();return Py()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function ii(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Zl();let e=Xl(n);return e?ni.resolve(e):Zl()}var Cy="docs";function oi(){return O.join(ii(),Cy)}function te(){return O.join(oi(),".index")}function td(){return O.join(te(),"build.lock")}function Go(){return O.join(te(),"build-status.json")}function si(){return O.join(te(),"build-meta.json")}function An(){return O.join(te(),"search.db")}function zt(){return O.join(te(),".tmp")}function Dy(){return O.join(ii(),"logs")}function qt(){return O.join(Dy(),"doc-init.log")}function Iy(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function nd(n,e){return O.dirname(Iy(n,e))}function Ay(){let n=ed(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?nd(n,e):O.join(e,"..","..","..")}function xy(...n){let e=ed(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(nd(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function rd(...n){for(let e of xy(...n))if(Ql.existsSync(e))return e;return null}function Je(){return rd("docs.zip")}function Vo(){return rd("index.zip")}function id(){return O.join(Ay(),"index","data")}import*as Ne from"fs";import*as mt from"path";var ht=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ai=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function od(n){return n instanceof ai}var Yo=null;function Jo(n){Yo=n}function Ko(){if(Yo)return Yo;let n=te();if(ht.every(i=>Ne.existsSync(mt.join(n,i))))return n;let t=id();if(ht.every(i=>Ne.existsSync(mt.join(t,i))))return t;throw new ai("Lexicon files not found. Install the documentation index first (index.zip).")}function sd(){Ko()}function Gt(n){let e=mt.join(Ko(),n);return Ne.readFileSync(e,"utf-8")}function ad(n,e){return Ne.readFileSync(mt.join(e,n),"utf-8")}async function cd(n,e=Ko()){await Ne.promises.mkdir(n,{recursive:!0});for(let t of ht){let r=mt.join(e,t),i=mt.join(n,t);await Ne.promises.copyFile(r,i)}}import*as ci from"fs";import*as ld from"path";import*as dd from"yauzl";var xn=null;function Ty(n){return new Promise((e,t)=>{dd.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function ky(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Ry(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=ky(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function My(){xn?.zipfile.close(),xn=null}async function Oy(n){let e=ld.resolve(n),t=await ci.promises.stat(e),r=xn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;My();let i=await Ty(e),o=await Ry(i);return xn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},xn}function Ly(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function Ny(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await Ly(n.zipfile,e)}finally{r()}}function _y(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function Hy(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function ud(n){let e=Je();if(!e)throw new Error("docs.zip not found");let t=await Oy(e),r=Hy(t.entries,_y(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Ny(t,r)).toString("utf-8")}function Zo(){let n=Je();return n!==null&&ci.existsSync(n)}import*as K from"fs";import*as Ke from"path";import pd from"adm-zip";var md=["search.db","build-meta.json",...ht],Fy=["corpus.json","corpus-offsets.json","orama.dpack"];async function jy(n){for(let e of Fy)await K.promises.rm(Ke.join(n,e),{force:!0})}async function $y(n){let e=await K.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await K.promises.rm(Ke.join(n,t.name),{recursive:!0,force:!0})}function By(n){let t=new pd(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function Wy(n){let e=te();await K.promises.mkdir(e,{recursive:!0});for(let t of md){let r=Ke.join(e,t);await K.promises.rm(r,{force:!0}),await K.promises.rename(Ke.join(n,t),r)}await jy(e),await K.promises.rm(zt(),{recursive:!0,force:!0})}function Xo(){let n=Vo();return n!==null&&K.existsSync(n)}async function hd(n){let e=Vo();if(!e)throw new Error("index.zip not found");let t=By(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=zt();await K.promises.rm(r,{recursive:!0,force:!0}),await K.promises.mkdir(r,{recursive:!0});let i=new pd(e);for(let s of md){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await K.promises.writeFile(Ke.join(r,s),a.getData())}let o=JSON.parse(await K.promises.readFile(Ke.join(r,"build-meta.json"),"utf-8"));if(!K.existsSync(Ke.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Wy(r),await K.promises.mkdir(oi(),{recursive:!0}),await $y(oi()),o}import{createHash as fd}from"crypto";import*as gd from"fs";async function li(n){return new Promise((e,t)=>{let r=fd("sha256"),i=gd.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function yd(n){return fd("sha256").update(n,"utf8").digest("hex")}var Qo=null;function Uy(){let n=Gt("harmonyos-synonyms.json");return JSON.parse(n)}function zy(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function qy(){let n=zy(Uy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Gy(){return Qo||(Qo=qy()),Qo}function es(n,e){let t=Gy(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function vd(n,e){let t=e?ad(n,e):Gt(n);return yd(t)}function di(n){return vd("harmonyos-synonyms.json",n)}function ui(n){return vd("harmonyos-terms.txt",n)}var Vy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function pi(){try{let n=await Ee.promises.readFile(Go(),"utf-8");return JSON.parse(n)}catch{return{...Vy}}}async function ts(n){let e=Go();await Ee.promises.mkdir(Tn.dirname(e),{recursive:!0}),await Ee.promises.writeFile(e,JSON.stringify(n,null,2))}function wd(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Ze(n){let t={...await pi(),...n,updatedAt:Date.now()};return await ts(t),t}async function ns(){let n=Je();return n?li(n):null}async function rs(){try{let n=await Ee.promises.readFile(si(),"utf-8");return JSON.parse(n)}catch{return null}}async function is(n=!1){if(n)return"no-index";let e=await rs();if(!e||e.segmentCount===0)return"no-index";let t=await ns();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ei?"engine-upgraded":e.termsHash!==ui()?"terms-changed":e.synonymsHash!==di()?"synonyms-changed":null}function kn(){if(!Zo()||!Ee.existsSync(An())||!Ee.existsSync(si()))return!1;let n=Tn.dirname(An());if(!ht.every(e=>Ee.existsSync(Tn.join(n,e))))return!1;try{let e=Ee.readFileSync(si(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function os(n=!1){return n?!0:Zo()?kn()?await is()!==null:!0:!1}async function bd(){let n=await pi();return["installing","indexing","persisting"].includes(n.state)}import*as Z from"fs";import*as Cu from"os";import*as ie from"path";var Sd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ss=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ed=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Pd=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var Yy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Jy=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Ky=/[A-Z][a-zA-Z0-9]{2,}/g,Zy=/@[A-Z][a-zA-Z0-9]*/g,Xy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Cd=6,Qy=/^[a-z][a-z0-9]{2,}$/,ev=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,tv=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,nv=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,rv=/^[A-Z][a-zA-Z0-9]+$/;function iv(n){return`"${n.replace(/"/g,'""')}"`}function Mn(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(iv).join(` ${e} `)}function Rn(n){return Mn(n,"OR")}function Dd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Rn([...t,...r]):`(${Rn(t)}) AND (${Rn(r)})`}function On(n){return tv.test(n)}function Id(n){return nv.test(n)&&n.length>=Cd}function ov(n){return rv.test(n)}function Ln(n){return On(n)||Id(n)||ov(n)}function sv(n){let e=n.trim().toLowerCase();return Pd.has(e)?!1:Sd.has(e)}function av(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function mi(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function as(n){return[...n.matchAll(Yy)].map(e=>e[0])}function cs(n,e=Cd){let t=[];for(let r of n.matchAll(Jy))r[0].length>=e&&t.push(r[0]);return t}function Vt(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function Pe(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function cv(n){let e=new Set;Pe(e,n);let t=mi(n);return t&&Pe(e,t),Vt([...e])}function hi(n){if(On(n))return cv(n);let e=new Set;return Pe(e,n),Vt([...e])}function fi(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(ev);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!Qy.test(r)||Ed.has(r)||!sv(i))return null;let o=av(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function ls(n){let e=fi(n.trim());return!e||e.second!=="manager"?null:e}function lv(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Ad(n){let e=n.trim(),t=ls(e);if(t&&ss.has(t.first))return!0;if(Id(e)){let r=lv(e);return r!==null&&ss.has(r)}return!1}function ds(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function us(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set;for(let r of as(n)){Pe(t,r);let i=mi(r);i&&Pe(t,i)}for(let r of cs(n))Pe(t,r);for(let r of n.matchAll(Zy))t.add(r[0]);for(let r of n.matchAll(Xy))t.add(r[0]);for(let r of n.matchAll(Ky))r[0].length>=4&&t.add(r[0]);return Vt([...t])}function xd(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set,r=fi(e);r&&Pe(t,r.camelCase);for(let i of us(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Vt([...t])}function Td(n){return Ln(n)}var _={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function kd(n){return _.pureApiSymbol.test(n.trim())}function Nn(n){let e=n.trim();return _.stageModelExact.test(e)||_.stageModelEnglishExact.test(e)}function Rd(n){let e=[];return Nn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),_.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),_.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Md(n){return Nn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var dv=[{matches:n=>_.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Nn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Nn(n)&&_.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>_.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>_.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>_.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>_.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>_.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>_.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function uv(n,e){for(let{catalog:t,multiplier:r}of e){let i=Ye[t];n.set(i,(n.get(i)??1)*r)}}function Od(n,e){for(let t of dv)t.matches(n)&&uv(e,t.weights)}function Ld(n,e){if(e!==void 0)return!1;let t=n.trim();return On(t)||_.pureApiSymbol.test(t)||Ad(t)}function Nd(n){let e=n.trim();if(On(e)||_.pureApiSymbol.test(e))return"harmonyos-references";if(Nn(e)||_.uiAbilityLifecycleCatalog.test(e)||_.stateDecoratorCatalog.test(e)||_.stateManagement.test(e)||_.declarePermissionCatalog.test(e)||_.stageModelEntryPage.test(e)||_.routerRoute.test(e)||_.dialogPopupExact.test(e))return"harmonyos-guides"}import{Jieba as pv}from"@node-rs/jieba";import{dict as mv}from"@node-rs/jieba/dict.js";var gi=null,ps=null,ms=null;function hv(){if(gi)return gi;let n=Gt("harmonyos-stopwords.txt");return gi=new Set(n.split(`
1295
+ `);i&&(e.isError?t.push(i):r.push(i))}setProjectPath(e){this.config.projectPath=e,this.arktsCheckTool&&(this.arktsCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown ArktsCheckTool during setProjectPath:",t)}),this.arktsCheckTool=null),this.cppCheckTool&&(this.cppCheckTool.shutdown().catch(t=>{h.warn("Failed to shutdown CppCheckTool during setProjectPath:",t)}),this.cppCheckTool=null),this.initPromise?(this.needsReinit=!0,h.info("Project path changed while init is running, will reinit after current init completes")):(this.projectState=0,this.ensureProjectReady().catch(t=>{h.warn("Failed to re-init project after setProjectPath:",t)}))}async start(){this.toolRouter.registerToServer(this.server);let e=new ly;if(await this.server.connect(e),h.info("devecocli-mcp-server started"),!this.config.debug){let t=Kc();t&&h.info(`Log file: ${t}`)}if(this.setupStdinCloseHandler(),this.config.projectPath)this.workspaceRoot=this.config.projectPath;else{let t=await this.getProjectRootFromClient();if(t){this.workspaceRoot=t;let r=Re(t);r?(h.info(`Detected project path from client root: ${r}`),this.config.projectPath=r,this.sdkPath=this.computeSdkPath()):h.warn(`Client root '${t}' is not a HarmonyOS project`)}else this.originalProjectPath?h.warn(`PROJECT_PATH '${this.originalProjectPath}' was provided but no HarmonyOS project was found in it`):h.info("project path is empty (no PROJECT_PATH env and client did not provide roots)")}this.ensureProjectReady().catch(t=>{h.warn("Background project init failed:",t)}),this.initializeCppCheck()}async getProjectRootFromClient(){try{let t=(await this.server.server.listRoots()).roots?.[0];if(!t)return h.warn("Client did not provide any roots"),null;let r=t.uri;return this.resolveFileUri(r)}catch(e){return h.warn("Failed to list roots from client:",e),null}}resolveFileUri(e){try{let t=new URL(e);if(t.protocol==="file:"){let r=t.pathname;return process.platform==="win32"&&/^\/[A-Za-z]:/.test(r)?r.substring(1):r}}catch(t){h.warn("Failed to parse URI with URL API, falling back to manual parsing:",t)}if(e.startsWith("file://")){let t=e.substring(7);return t=decodeURIComponent(t),process.platform==="win32"&&t.startsWith("/")&&/^[A-Za-z]:/.test(t.substring(1))&&(t=t.substring(1)),t}return e}setupStdinCloseHandler(){let e=!1,t=()=>{e||(e=!0,h.info("stdin closed (MCP client disconnected), shutting down..."),this.shutdown().then(()=>{h.info("shutdown completed, exiting process"),process.exit(0)}).catch(r=>{h.error("shutdown failed:",r),process.exit(1)}))};process.stdin.on("end",t),process.stdin.on("close",t)}initializeCppCheck(){let e=this.config.projectPath;if(!e){h.warn("C++ LSP initialization skipped: project path is not configured");return}this.cppCheckTool=new Bt(e,this.config.devecoPath??null),h.info("CppCheckTool created (lazy initialization)")}async ensureProjectReady(){if(!this.initPromise){this.initPromise=this.doEnsureProjectReady();try{await this.initPromise}finally{this.initPromise=null}this.needsReinit&&(this.needsReinit=!1,this.projectState=0,this.ensureProjectReady().catch(e=>{h.warn("Failed to re-init project after needsReinit:",e)}))}}discoverProject(){if(!((this.projectState===0||this.projectState===5)&&!this.config.projectPath))return!0;this.projectState=1;let t=this.workspaceRoot?Re(this.workspaceRoot):null;return!t&&this.originalProjectPath&&(t=Re(this.originalProjectPath),t&&h.info(`Phase 1 found HarmonyOS project from original config: ${t}`)),t?(this.config.projectPath=t,this.sdkPath=this.computeSdkPath(),this.initRetryCount=0,!0):(this.projectState=0,!1)}async doEnsureProjectReady(){if(this.discoverProject()&&(this.sdkPath||(this.sdkPath=this.computeSdkPath()),!!await this.ensureProjectSynced())){this.projectState=3,this.arktsCheckTool=new $t(this.config.projectPath,this.config.devecoPath??null,this.config.nodeMaxOldSpaceSize),this.arktsCheckTool.setOnConfigChanged(()=>{h.info("Config files changed, resetting to IDLE state for reinit"),this.configChangedTriggeredResync=!0,this.needsReinit=!0,this.projectState=0});try{await this.arktsCheckTool.initialize(),this.projectState=4,this.initRetryCount=0,h.info("Project fully initialized, check tool is available")}catch(e){h.error("LSP initialization failed:",e),this.arktsCheckTool=null,this.initRetryCount++,this.projectState=5}}}async ensureProjectSynced(){let e=this.config.projectPath,t=El(e);return t.required?(h.info(`Sync required: ${t.reason}`),this.runSync(e)):(h.info(`Sync skipped: ${t.reason}`),!0)}async runSync(e){this.projectState=2,h.info("Starting project sync...");let t=await jt.handleSyncProject(e,this.sdkPath);switch(t.status){case"success":return this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,!0;case"skipped":{this.syncSkippedDueToLock=!0,this.syncSkipStartedAt===0&&(this.syncSkipStartedAt=Date.now());let r=Date.now()-this.syncSkipStartedAt,i=Math.round(r/1e3);return r>=Pl?(h.error(`Sync skipped for ${i}s due to lock contention, giving up`),this.initRetryCount++,this.syncSkipStartedAt=0,this.projectState=5,!1):(h.warn(`Sync skipped: ${t.reason}, resetting to IDLE for retry (elapsed ${i}s / ${Pl/1e3}s)`),this.projectState=0,!1)}case"failed":return h.error(`Project sync failed: ${t.reason}`),this.syncSkippedDueToLock=!1,this.syncSkipStartedAt=0,this.initRetryCount++,this.projectState=5,!1}}computeSdkPath(){let e=fr(this.config.devecoPath??""),t=de(e);return ut.join(t,"sdk")}async shutdown(){this.arktsCheckTool&&await this.arktsCheckTool.shutdown(),this.cppCheckTool&&await this.cppCheckTool.shutdown();try{await this.server.close()}catch(e){h.warn("Failed to close MCP server connection:",e)}h.info("devecocli-mcp-server stopped"),Jc(),Yc()}getToolRouter(){return this.toolRouter}getServer(){return this.server}};function dy(n){let e=[],t=[],r=[];for(let i of n)ut.extname(i).toLowerCase()===".ets"?e.push(i):gr(i)?t.push(i):r.push(i);return{etsFiles:e,cppFiles:t,unsupported:r}}function jo(n={}){return new Qr(n)}import*as $o from"fs";import*as Wt from"path";import{spawn as uy}from"child_process";async function Dl(n){fn(!1);let{serverPath:e,logPath:t,projectPath:r,sdkPath:i,serverMaxSize:o}=await py(n),s=gy(e,t,r,i,o);h.info("ace-server started, bridging stdio (initialize is left to the client)"),vy(s)}async function py(n){let e=await my();e||(h.error("DevEco Studio not found. Ensure DevEco Studio is installed."),process.exit(1));let t=ue(n.projectPath??process.cwd()),r=Wt.join(de(e),"sdk"),i=It(e);i||(h.error("ace-server not found in DevEco Studio installation."),process.exit(1));let o=Wt.resolve(i,"ace-server","out","standardIndex","index.js"),s=Wt.join(At(),"lsp-server",String(Date.now()));$o.mkdirSync(s,{recursive:!0});let a=hy(t,r);return h.info(`projectPath=${t}, sdkPath=${r}, serverPath=${o}, logPath=${s}, serverMaxSize=${a}MB`),{projectPath:t,sdkPath:r,serverPath:o,logPath:s,serverMaxSize:a}}function my(){return N.new().then(n=>n.devecoStudioPath).catch(()=>be())}function hy(n,e){let t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=t?parseInt(t,10):NaN,i=Number.isFinite(r)&&r>0?r:void 0,o=fy(n,e),s=Sr(o,i);return h.info(`[serve-lsp] serverMaxSize=${s}MB (moduleCount=${o}, override=${i??"none"})`),s}function fy(n,e){try{let t=[];return new dt(n,e).getAllDependencyMap(t).status==="OK"?t.length:new Oe(n).getAllModuleInfo().length}catch{return 0}}function gy(n,e,t,r,i){let o=Wt.join(e,"lspLog");$o.mkdirSync(o,{recursive:!0});let s=yy(n,o,t,r,i),a=process.execPath??"node";return h.info(`[serve-lsp] spawn: ${a} ${s.join(" ")}`),uy(a,s,{cwd:t,stdio:["pipe","pipe","pipe"],windowsHide:!0})}function yy(n,e,t,r,i){let o=j(e);return["--expose-gc",`--max-old-space-size=${i}`,"--report-on-fatalerror","--report-uncaught-exception",`--report-filename=nodejs_error_${Date.now()}.txt`,`--report-dir=${o}`,n,"--stdio",`--logger-path=${o}`,"--logger-level=TRACE",`--projectPath=${j(t)}`,`--sdkPath=${j(r)}`]}function vy(n){n.stdout?.on("data",e=>process.stdout.write(e)),n.stderr?.on("data",e=>{h.error(`[ace-server] ${e.toString("utf8").trim()}`)}),process.stdin.on("data",e=>{n.stdin?.write(e)}),process.stdin.on("end",()=>{h.info("Editor disconnected, shutting down"),n.kill(),process.exit(0)}),n.on("exit",e=>{h.info(`ace-server exited with code ${e}`),process.exit(e??0)})}async function by(){let n=process.env.PROJECT_PATH||"",e=process.env.DEVECO_PATH,t=process.env.NODE_MAX_OLD_SPACE_SIZE,r=process.env.DEBUG==="true"||process.env.DEBUG==="1",i=await N.new(),o=n,s=e??i.devecoStudioPath,a=jo({projectPath:o,devecoPath:s,nodeMaxOldSpaceSize:t,debug:r}),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(l){console.error("Failed to start MCP server:",l),process.exit(1)}}var Bo=new wy("serve").description("Host bundled auxiliary protocol servers");Bo.command("mcp").description("Start a local stdio-based MCP server").action(async()=>{await by()});Bo.command("lsp").description("Start a bundled LSP language server").option("--arkts","Start the ArkTS language server (ace-server)").option("--project-path <path>","HarmonyOS project root path",process.cwd()).action(async n=>{n.arkts||(console.error("Use --arkts to start the ArkTS language server."),process.exit(1)),await Dl({projectPath:n.projectPath})});var Il=Bo;import{Command as wb,InvalidArgumentError as As}from"commander";import{red as xi,dim as bb}from"colorette";import*as z from"fs";import*as Jt from"path";import rb from"adm-zip";import ib from"proper-lockfile";import Ru from"ora";import*as Ee from"fs";import*as Tn from"path";var Ve=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],pt={"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 ei="1.9.1",fR=100*1024*1024,Al=280,xl=6,Tl=100,kl=3,Rl=28,Wo=10,Ml=/API参考|APIReference/i,In=200,Ol=12,Ll=4,Uo=8,Nl=6,ti=700,zo=250,qo=400,_l=1320,Hl=120,Fl=450,jl=250,$l=500,Bl=480,Wl=80,Ul=200,zl=60,ql=200,Gl=40,Vl=200,Yl=200,Jl=40,Ut=500,Kl=Object.fromEntries(Ve.map((n,e)=>[pt[n],e])),Ye=Object.fromEntries(Ve.map((n,e)=>[n,e]));import*as Ql from"fs";import*as O from"path";import{fileURLToPath as ed}from"url";import*as ni from"path";import{homedir as Sy}from"os";var Ey="deveco-cli";function Xl(n){let e=n.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Py(){let n=process.env.DEVECO_CLI_DATA_DIR;return n!==void 0&&Xl(n)!==""}function Zl(){return ni.join(Sy(),".local","share",Ey)}function ri(n){let e=ii();return Py()?[`Data directory (DEVECO_CLI_DATA_DIR): ${e}`,"If you changed this in System Environment Variables, open a new terminal and retry.",`Log file: ${n}`]:[`Data directory (default): ${e}`,"To use a custom location, set DEVECO_CLI_DATA_DIR and open a new terminal.",`Log file: ${n}`]}function ii(){let n=process.env.DEVECO_CLI_DATA_DIR;if(n===void 0||n==="")return Zl();let e=Xl(n);return e?ni.resolve(e):Zl()}var Cy="docs";function oi(){return O.join(ii(),Cy)}function te(){return O.join(oi(),".index")}function td(){return O.join(te(),"build.lock")}function Go(){return O.join(te(),"build-status.json")}function si(){return O.join(te(),"build-meta.json")}function An(){return O.join(te(),"search.db")}function zt(){return O.join(te(),".tmp")}function Dy(){return O.join(ii(),"logs")}function qt(){return O.join(Dy(),"doc-init.log")}function Iy(n,e){let t=e;for(;!t.endsWith(`${O.sep}dist`)&&t!==O.dirname(t);)t=O.dirname(t);return t}function nd(n,e){return O.dirname(Iy(n,e))}function Ay(){let n=ed(import.meta.url),e=O.dirname(n);return n.includes(`${O.sep}dist${O.sep}`)?nd(n,e):O.join(e,"..","..","..")}function xy(...n){let e=ed(import.meta.url),t=O.dirname(e);return e.includes(`${O.sep}dist${O.sep}`)?[O.join(nd(e,t),...n)]:[O.join(t,"..","..","..",...n)]}function rd(...n){for(let e of xy(...n))if(Ql.existsSync(e))return e;return null}function Je(){return rd("docs.zip")}function Vo(){return rd("index.zip")}function id(){return O.join(Ay(),"index","data")}import*as Ne from"fs";import*as mt from"path";var ht=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],ai=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};function od(n){return n instanceof ai}var Yo=null;function Jo(n){Yo=n}function Ko(){if(Yo)return Yo;let n=te();if(ht.every(i=>Ne.existsSync(mt.join(n,i))))return n;let t=id();if(ht.every(i=>Ne.existsSync(mt.join(t,i))))return t;throw new ai("Lexicon files not found. Install the documentation index first (index.zip).")}function sd(){Ko()}function Gt(n){let e=mt.join(Ko(),n);return Ne.readFileSync(e,"utf-8")}function ad(n,e){return Ne.readFileSync(mt.join(e,n),"utf-8")}async function cd(n,e=Ko()){await Ne.promises.mkdir(n,{recursive:!0});for(let t of ht){let r=mt.join(e,t),i=mt.join(n,t);await Ne.promises.copyFile(r,i)}}import*as ci from"fs";import*as ld from"path";import*as dd from"yauzl";var xn=null;function Ty(n){return new Promise((e,t)=>{dd.open(n,{lazyEntries:!0,decodeStrings:!1,autoClose:!1},(r,i)=>{if(r||!i){t(r??new Error(`Failed to open zip: ${n}`));return}e(i)})})}function ky(n){let e=n.fileName;return(Buffer.isBuffer(e)?e.toString("utf-8"):String(e)).replace(/\\/g,"/")}function Ry(n){let e=new Map;return new Promise((t,r)=>{n.readEntry(),n.on("entry",i=>{let o=ky(i);o.endsWith("/")||e.set(o,i),n.readEntry()}),n.on("end",()=>{t(e)}),n.on("error",r)})}function My(){xn?.zipfile.close(),xn=null}async function Oy(n){let e=ld.resolve(n),t=await ci.promises.stat(e),r=xn;if(r&&r.zipPath===e&&r.mtimeMs===t.mtimeMs&&r.size===t.size)return r;My();let i=await Ty(e),o=await Ry(i);return xn={zipPath:e,mtimeMs:t.mtimeMs,size:t.size,zipfile:i,entries:o,readChain:Promise.resolve()},xn}function Ly(n,e){return new Promise((t,r)=>{n.openReadStream(e,(i,o)=>{if(i||!o){r(i??new Error(`Failed to read zip entry: ${e.fileName}`));return}let s=[];o.on("data",a=>{s.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),o.on("end",()=>{t(Buffer.concat(s))}),o.on("error",r)})})}async function Ny(n,e){let t=n.readChain,r;n.readChain=new Promise(i=>{r=i}),await t;try{return await Ly(n.zipfile,e)}finally{r()}}function _y(n){let e=n.replace(/\\/g,"/").replace(/\.md$/,"");return[`docs/${e}.md`,`${e}.md`,`docs/${e}`,e]}function Hy(n,e){for(let t of e){let r=n.get(t.replace(/\\/g,"/"));if(r)return r}return null}async function ud(n){let e=Je();if(!e)throw new Error("docs.zip not found");let t=await Oy(e),r=Hy(t.entries,_y(n));if(!r)throw new Error(`Document not found: ${n}`);return(await Ny(t,r)).toString("utf-8")}function Zo(){let n=Je();return n!==null&&ci.existsSync(n)}import*as K from"fs";import*as Ke from"path";import pd from"adm-zip";var md=["search.db","build-meta.json",...ht],Fy=["corpus.json","corpus-offsets.json","orama.dpack"];async function jy(n){for(let e of Fy)await K.promises.rm(Ke.join(n,e),{force:!0})}async function $y(n){let e=await K.promises.readdir(n,{withFileTypes:!0});for(let t of e)t.name!==".index"&&await K.promises.rm(Ke.join(n,t.name),{recursive:!0,force:!0})}function By(n){let t=new pd(n).getEntry("build-meta.json");if(!t)throw new Error("index.zip is missing build-meta.json");return JSON.parse(t.getData().toString("utf-8"))}async function Wy(n){let e=te();await K.promises.mkdir(e,{recursive:!0});for(let t of md){let r=Ke.join(e,t);await K.promises.rm(r,{force:!0}),await K.promises.rename(Ke.join(n,t),r)}await jy(e),await K.promises.rm(zt(),{recursive:!0,force:!0})}function Xo(){let n=Vo();return n!==null&&K.existsSync(n)}async function hd(n){let e=Vo();if(!e)throw new Error("index.zip not found");let t=By(e);if(t.docsZipSha256!==n)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(t.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=zt();await K.promises.rm(r,{recursive:!0,force:!0}),await K.promises.mkdir(r,{recursive:!0});let i=new pd(e);for(let s of md){let a=i.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await K.promises.writeFile(Ke.join(r,s),a.getData())}let o=JSON.parse(await K.promises.readFile(Ke.join(r,"build-meta.json"),"utf-8"));if(!K.existsSync(Ke.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Wy(r),await K.promises.mkdir(oi(),{recursive:!0}),await $y(oi()),o}import{createHash as fd}from"crypto";import*as gd from"fs";async function li(n){return new Promise((e,t)=>{let r=fd("sha256"),i=gd.createReadStream(n);i.on("data",o=>r.update(o)),i.on("error",t),i.on("end",()=>e(r.digest("hex")))})}function yd(n){return fd("sha256").update(n,"utf8").digest("hex")}var Qo=null;function Uy(){let n=Gt("harmonyos-synonyms.json");return JSON.parse(n)}function zy(n){let e=new Map;for(let t of n){let r=t.map(i=>i.trim()).filter(Boolean);for(let i of r){let o=r.filter(s=>s!==i);e.set(i.toLowerCase(),o),i!==i.toLowerCase()&&e.set(i,o)}}return e}function qy(){let n=zy(Uy()),e=new Map;for(let[t,r]of n)e.set(t,new Set(r));return e}function Gy(){return Qo||(Qo=qy()),Qo}function es(n,e){let t=Gy(),r=n.split(/\s+/).filter(Boolean),i=new Set,o=Number.isFinite(e)?e:r.length;for(let s=0;s<r.length&&i.size<o;s+=1){let a=r[s];i.add(a);let c=t.get(a)??t.get(a.toLowerCase());if(c)for(let l of c){if(i.size>=o)break;i.add(l)}}return[...i].join(" ")}function vd(n,e){let t=e?ad(n,e):Gt(n);return yd(t)}function di(n){return vd("harmonyos-synonyms.json",n)}function ui(n){return vd("harmonyos-terms.txt",n)}var Vy={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function pi(){try{let n=await Ee.promises.readFile(Go(),"utf-8");return JSON.parse(n)}catch{return{...Vy}}}async function ts(n){let e=Go();await Ee.promises.mkdir(Tn.dirname(e),{recursive:!0}),await Ee.promises.writeFile(e,JSON.stringify(n,null,2))}function wd(n){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:n,startedAt:e,updatedAt:e,error:null}}async function Ze(n){let t={...await pi(),...n,updatedAt:Date.now()};return await ts(t),t}async function ns(){let n=Je();return n?li(n):null}async function rs(){try{let n=await Ee.promises.readFile(si(),"utf-8");return JSON.parse(n)}catch{return null}}async function is(n=!1){if(n)return"no-index";let e=await rs();if(!e||e.segmentCount===0)return"no-index";let t=await ns();return t&&e.docsZipSha256!==t?"docs-changed":e.indexVersion!==ei?"engine-upgraded":e.termsHash!==ui()?"terms-changed":e.synonymsHash!==di()?"synonyms-changed":null}function kn(){if(!Zo()||!Ee.existsSync(An())||!Ee.existsSync(si()))return!1;let n=Tn.dirname(An());if(!ht.every(e=>Ee.existsSync(Tn.join(n,e))))return!1;try{let e=Ee.readFileSync(si(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function os(n=!1){return n?!0:Zo()?kn()?await is()!==null:!0:!1}async function bd(){let n=await pi();return["installing","indexing","persisting"].includes(n.state)}import*as Z from"fs";import*as Cu from"os";import*as ie from"path";var Sd=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]),ss=new Set(["wifi","wlan","notification","bluetooth","location","sensor","power","battery","account","pasteboard","calendar","telephony","contact"]),Ed=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Pd=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var Yy=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,Jy=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Ky=/[A-Z][a-zA-Z0-9]{2,}/g,Zy=/@[A-Z][a-zA-Z0-9]*/g,Xy=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,Cd=6,Qy=/^[a-z][a-z0-9]{2,}$/,ev=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,tv=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,nv=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,rv=/^[A-Z][a-zA-Z0-9]+$/;function iv(n){return`"${n.replace(/"/g,'""')}"`}function Mn(n,e){let t=[...new Set(n.filter(Boolean))];return t.length===0?'""':t.map(iv).join(` ${e} `)}function Rn(n){return Mn(n,"OR")}function Dd(n,e){let t=[...new Set(n.filter(Boolean))],r=[...new Set(e.filter(Boolean))];return t.length===0||r.length===0?Rn([...t,...r]):`(${Rn(t)}) AND (${Rn(r)})`}function On(n){return tv.test(n)}function Id(n){return nv.test(n)&&n.length>=Cd}function ov(n){return rv.test(n)}function Ln(n){return On(n)||Id(n)||ov(n)}function sv(n){let e=n.trim().toLowerCase();return Pd.has(e)?!1:Sd.has(e)}function av(n,e){let t=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${n.trim().toLowerCase()}${t}${r}`}function mi(n){let t=n.replace(/^@ohos\./i,"").split(".").filter(Boolean);return t[t.length-1]?.trim()||void 0}function as(n){return[...n.matchAll(Yy)].map(e=>e[0])}function cs(n,e=Cd){let t=[];for(let r of n.matchAll(Jy))r[0].length>=e&&t.push(r[0]);return t}function Vt(n){return n.filter(e=>{let t=e.toLowerCase();return!n.some(r=>{if(r===e)return!1;let i=r.toLowerCase();return i.length>t.length&&i.endsWith(t)&&t.length>=4})})}function Pe(n,e){let t=e.trim();if(!t)return;n.add(t);let r=t.toLowerCase();r!==t&&n.add(r)}function cv(n){let e=new Set;Pe(e,n);let t=mi(n);return t&&Pe(e,t),Vt([...e])}function hi(n){if(On(n))return cv(n);let e=new Set;return Pe(e,n),Vt([...e])}function fi(n){let e=n.trim();if(/[A-Z]/.test(e))return null;let t=e.match(ev);if(!t)return null;let r=t[1].toLowerCase(),i=t[2].toLowerCase();if(!Qy.test(r)||Ed.has(r)||!sv(i))return null;let o=av(r,i);return{first:r,second:i,camelCase:o,lower:o.toLowerCase()}}function ls(n){let e=fi(n.trim());return!e||e.second!=="manager"?null:e}function lv(n){let e=n.match(/^([a-z][a-z0-9]*)Manager$/i);return e?e[1].toLowerCase():null}function Ad(n){let e=n.trim(),t=ls(e);if(t&&ss.has(t.first))return!0;if(Id(e)){let r=lv(e);return r!==null&&ss.has(r)}return!1}function ds(n,e,t){let r=t.toLowerCase(),i=new RegExp(`@ohos\\.[^\\s(]*${t}`,"i");for(let o of[n,e])if(o&&(o.toLowerCase().includes(r)||i.test(o)))return!0;return!1}function us(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set;for(let r of as(n)){Pe(t,r);let i=mi(r);i&&Pe(t,i)}for(let r of cs(n))Pe(t,r);for(let r of n.matchAll(Zy))t.add(r[0]);for(let r of n.matchAll(Xy))t.add(r[0]);for(let r of n.matchAll(Ky))r[0].length>=4&&t.add(r[0]);return Vt([...t])}function xd(n){let e=n.trim();if(Ln(e))return hi(e);let t=new Set,r=fi(e);r&&Pe(t,r.camelCase);for(let i of us(e))t.add(i);for(let i of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let o=i[0];o!==o.toLowerCase()&&t.add(o)}return Vt([...t])}function Td(n){return Ln(n)}var _={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function kd(n){return _.pureApiSymbol.test(n.trim())}function Nn(n){let e=n.trim();return _.stageModelExact.test(e)||_.stageModelEnglishExact.test(e)}function Rd(n){let e=[];return Nn(n.trim())&&e.push("Stage\u6A21\u578B","Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0"),_.declarePermissionTokens.test(n)&&e.push("\u58F0\u660E\u6743\u9650"),_.stageModelEntryPage.test(n)&&e.push("\u9875\u9762\u8DEF\u7531","pushUrl"),/UIAblity|UIAbility/.test(n)&&/生命周期/.test(n)&&e.push("UIAbility\u7EC4\u4EF6\u751F\u547D\u5468\u671F"),e}function Md(n){return Nn(n)?{expandedQuery:"Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0",tokens:["Stage\u6A21\u578B\u5F00\u53D1\u6982\u8FF0","Stage\u6A21\u578B"]}:null}var dv=[{matches:n=>_.uiAbilityLifecycleBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:n=>Nn(n),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:n=>!Nn(n)&&_.stageModel.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:n=>_.entryAbilityPage.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:n=>_.declarePermissionBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:n=>_.stateDecoratorBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:n=>_.stateManagement.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:n=>_.routerRoute.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:n=>_.dialogPopupBoost.test(n),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function uv(n,e){for(let{catalog:t,multiplier:r}of e){let i=Ye[t];n.set(i,(n.get(i)??1)*r)}}function Od(n,e){for(let t of dv)t.matches(n)&&uv(e,t.weights)}function Ld(n,e){if(e!==void 0)return!1;let t=n.trim();return On(t)||_.pureApiSymbol.test(t)||Ad(t)}function Nd(n){let e=n.trim();if(On(e)||_.pureApiSymbol.test(e))return"harmonyos-references";if(Nn(e)||_.uiAbilityLifecycleCatalog.test(e)||_.stateDecoratorCatalog.test(e)||_.stateManagement.test(e)||_.declarePermissionCatalog.test(e)||_.stageModelEntryPage.test(e)||_.routerRoute.test(e)||_.dialogPopupExact.test(e))return"harmonyos-guides"}import{Jieba as pv}from"@node-rs/jieba";import{dict as mv}from"@node-rs/jieba/dict.js";var gi=null,ps=null,ms=null;function hv(){if(gi)return gi;let n=Gt("harmonyos-stopwords.txt");return gi=new Set(n.split(`
1296
1296
  `).map(e=>e.trim()).filter(Boolean)),gi}function fv(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t]?.trim();if(!r)continue;let i=n[t+1]?.trim();if(r==="@"&&i&&/^[A-Z][a-zA-Z0-9]*$/.test(i)){e.push(`@${i}`),t+=1;continue}e.push(r)}return e}function _d(n){let e=hv(),t=[];for(let r of fv(n)){let i=r.trim();!i||e.has(i)||(t.push(i.toLowerCase()),/[A-Z]/.test(i)&&/[a-zA-Z]/.test(i)&&t.push(i))}return t}async function gv(){let n=pv.withDict(mv),e=Gt("harmonyos-terms.txt");return n.loadDict(Buffer.from(e,"utf-8")),n}async function Xe(){return ps||(ms||(ms=gv().then(n=>(ps=n,n))),ms)}async function yv(n){let e=await Xe();return _d(e.cutForSearch(n,!0))}async function Hd(n){let e=await Xe();return _d(e.cut(n,!0))}async function yi(n,e){let t=n.trim();if(!t||e<=0)return"";let r=(await yv(t)).join(" ");return r.length<=e?r:r.slice(0,e)}async function vv(n,e){let t=[];for(let i of n){let o=i.trim();o&&(t.push(o.toLowerCase()),/[A-Z]/.test(o)&&t.push(o))}let r=[...new Set(t)].join(" ");return r.length<=e?r:r.slice(0,e)}async function vi(n){let e=!!n.sectionTitle.trim(),t=n.titleTokens.trim(),r=e?Bl:_l,i=e?Ul:Fl,o=e?await vv(n.apiSymbols,i):await yi(n.apiSymbols.join(" "),i),a=(await Promise.all([yi(t,e?Wl:Hl),Promise.resolve(o),yi(n.headingsText,e?zl:jl),yi(n.bodySample,e?ql:$l)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}function wv(n){return n.join(" ").replace(/\s+/g," ").trim().slice(0,In)}function hs(n,e){let t=new Set,r=[];for(let i of[...n,...e]){let o=i.toLowerCase();if(!(!i||t.has(o))&&(t.add(o),r.push(i),r.length>=Ol))break}return r}function bv(n){return n.length>=2&&n.length<=Ll}function Sv(n,e){let t=es(n,Uo),r=t.split(/\s+/).filter(Boolean),i=[e.first,...r.filter(a=>a!==e.second),e.lower,e.camelCase],o=[e.second,e.lower,e.camelCase],s=hs(i,o);return{rawQuery:n,expandedQuery:t,tokens:s,preferAnd:!1,ftsMatch:Dd(i,o)}}function Ev(n,e){let t=hs(hi(e),[]);return{rawQuery:n,expandedQuery:n,tokens:t,preferAnd:!1,ftsMatch:Rn(t)}}async function Fd(n){let e=wv(n),t=e.trim(),r=Md(t);if(r)return{rawQuery:e,expandedQuery:r.expandedQuery,tokens:r.tokens,preferAnd:!1};let i=fi(t);if(i)return Sv(e,i);if(Ln(t))return Ev(e,t);let o=Rd(e),s=[...us(e),...o],c=Td(t)?e:es(e,Uo),l=await Hd(c),u=hs(s,l);return{rawQuery:e,expandedQuery:c,tokens:u,preferAnd:o.length===0&&bv(u)}}var jd=["harmonyos-releases","harmonyos-roadmap"],Pv=new Set(jd.map(n=>Ye[n])),Cv=jd.map(n=>`${pt[n]}/`);function Dv(n){return Pv.has(n)}function Iv(n){return Cv.some(e=>n.startsWith(e))}function $d(n){let e=[],t=[];for(let r of n)Dv(r.catalog_id)?t.push(r):e.push(r);return[...e,...t]}function Bd(n){let e=[],t=[];for(let r of n)Iv(r.documentId)?t.push(r):e.push(r);return[...e,...t]}var Av=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function _n(n,e,t){let r=Ye[e];n.set(r,(n.get(r)??1)*t)}function xv(n,e){let t=n.trim(),r=/[\u4e00-\u9fff]/.test(t),i=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(t),o=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(t);if(r&&(i||o)){_n(e,"harmonyos-guides",1.45),_n(e,"harmonyos-references",1.35);return}(i||o)&&_n(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(t)&&_n(e,"harmonyos-references",1.75)}function Wd(n){let e=new Map,t=n.trim();if(!t)return e;let r=kd(t);xv(t,e),Od(t,e);for(let i of Av)i.pattern.test(t)&&(i.skipForPureApiSymbol&&r||_n(e,i.catalog,i.multiplier));return e}function Ud(n){return Nd(n)}var Tv=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function zd(n,e){let t=-1;for(let r of Tv){let i=n.lastIndexOf(r);i>t&&(t=i)}return t>=e?t:-1}function qd(n,e){let t=n.trim();if(t.length<=e)return{text:t,excerptTruncated:!1};let r=t.slice(0,e),i=zd(r,e-20),o=i>=0?i:e;return{text:t.slice(0,o).trimEnd(),excerptTruncated:!0}}function Gd(n,e,t={}){let{maxLen:r=Yl,contextChars:i=Jl,excerptTruncated:o=!1}=t,s=n.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return o?`${s}...`:s;let a=e.split(/\s+/).map(he=>he.trim()).filter(Boolean),c=0;for(let he of a){let Wn=s.toLowerCase().indexOf(he.toLowerCase());if(Wn>=0){c=Wn;break}}let l=Math.max(0,c-i),u=Math.min(s.length,l+r),f=s.slice(l,u),P=zd(f,r-25);P>=0&&(u=l+P);let C=s.slice(l,u).trim(),L=l>0?"...":"",ne=u<s.length||o?"...":"";return`${L}${C}${ne}`}var kv=`
1297
1297
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
1298
1298
  d.catalog_id, bm25(segments_fts) AS bm25
@@ -1363,4 +1363,4 @@ CREATE INDEX segments_doc_id_idx ON segments(doc_id);
1363
1363
  Detail: ${n.message}`):n}try{await Xe()}catch(n){let e=n instanceof Error?n.message:String(n);throw new $n(`${tb()}
1364
1364
 
1365
1365
  Detail: ${e}`)}try{await Hn()}catch(n){let e=n instanceof Error?n.message:String(n);throw new $n(nb(e))}}var Ps=class extends Error{constructor(t,r){super(r);this.code=t;this.name="DocNotReadyError"}code};function ob(n){return new Promise(e=>setTimeout(e,n))}async function sb(n){let e=qt();await z.promises.mkdir(Jt.dirname(e),{recursive:!0}),await z.promises.appendFile(e,`${new Date().toISOString()} ${n}
1366
- `)}async function ab(n){let e=Je();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 rb(e).extractAllTo(n,!0),await Au(n)}async function cb(){let n=te(),e=zt(),t=await z.promises.readdir(e);for(let r of t){let i=Jt.join(n,r);await z.promises.rm(i,{force:!0}),await z.promises.rename(Jt.join(e,r),i)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Jt.join(n,"orama.dpack"),{force:!0})}async function lb(n,e){e?.start("Installing documentation index\u2026"),await Ze({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await hd(n),e&&(e.text="Documentation index installed.")}async function db(n,e,t){let r=zt(),i=await Iu();await z.promises.mkdir(te(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ze({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ab(i),await Du({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:ui(),synonymsHash:di(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Ze({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await z.promises.rm(i,{recursive:!0,force:!0})}await Ze({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await cb(),eu()}async function Tu(n){await Ze({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function ub(n){let e=await rs(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ze({state:"done",message:t,error:null})}async function pb(n,e){let t=n instanceof Error?n.message:String(n);throw await Ze({state:"error",error:t}),await sb(`ERROR: ${t}`),e?.fail(t),n}async function mb(){let n=te();await z.promises.mkdir(n,{recursive:!0});let e=td();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function hb(){let n=await mb();return ib.lock(n,{stale:1800*1e3})}async function fb(){let n=Je(),e=(n?await li(n):null)??await ns();if(!e)throw new Error("docs.zip not found");return e}async function gb(n,e){let t=await fb(),r=n.force||await os(n.force),i=await is(n.force);if(!r&&!i&&kn()){await ub(e);return}if(Xo()&&!n.force){await lb(t,e),await Tu(e);return}await db(n,t,e),await Tu(e)}var Cs=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Ru({text:"Checking documentation\u2026",color:"cyan"}),o;try{o=await hb(),await ts(wd("Starting documentation setup\u2026")),await gb(e,i)}catch(s){return pb(s,i)}finally{o&&await o()}}};async function yb(n){for(;;){let e=await pi();if(e.state==="done"&&kn())return;if(e.state==="error")throw new Ps("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 ob(500)}}async function ku(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Cs.run({builtBy:"doc-init",force:e,quiet:!0})}async function vb(){if(kn())return;let n=Ru({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await bd()){await yb(n),n.succeed("Documentation ready.");return}if(await os()){await ku(n),n.succeed("Documentation ready.");return}await ku(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function Bn(){await vb(),await xu()}var Ds=class{async search(e,t,r=20){return await Bn(),ru(e,t,r)}async readDocument(e){return await Bn(),ud(e)}},Is=new Ds;function Mu(...n){return e=>{if(!n.includes(e))throw new As(`Allowed values: ${n.join(", ")}`);return e}}function Sb(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new As("Must be a positive integer.");return e}var Eb=Mu("json","default"),Pb=Mu("json","default"),Ti=new wb("docs").description("Search and read HarmonyOS documentation from local docs directory");Ti.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Db,"all").option("--format <fmt>","Output format (default, json)",Eb,"default").option("--limit <n>","Max number of results",Sb,20).action(async(n,e)=>{try{let t=Cb(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await Is.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):Ib(i)}catch(t){console.error(xi(t.message)),process.exit(1)}});Ti.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(xi("Document ID cannot be empty.")),process.exit(1));let t=await Is.readDocument(e);console.log(t)}catch(e){console.error(xi(e.message)),process.exit(1)}});Ti.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Pb,"default").action(async n=>{try{if(await Bn(),n.format==="json"){let e=Ve.map(t=>({name:t,title:pt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Ve)console.log(` ${e.padEnd(20)} ${bb(pt[e])}`)}catch(e){console.error(xi(e.message)),process.exit(1)}});function Cb(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>In)throw new Error(`Query exceeds ${In} characters.`);return e}function Db(n){if(n==="all")return"all";if(!Ve.includes(n))throw new As(`Invalid catalog "${n}". Allowed: all, ${Ve.join(", ")}`);return n}function Ib(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 Ou=Ti;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Ab();X.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.3");X.addCommand(Bs);X.addCommand(Js);X.addCommand(Qs);X.addCommand(ua);X.addCommand(Na);X.addCommand(Ba);X.addCommand(mc);X.addCommand(yc);X.addCommand(Ac);X.addCommand(Nc);X.addCommand(Il);X.addCommand(Ou);var xs=process.argv.slice(2);xs.length>=2&&xs[xs.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Tb=new Set(["update"]);X.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==X;)t=t.parent;Tb.has(t.name())||await N.checkVersion()});X.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(xb(`Error: ${e}`)),process.exit(1)});
1366
+ `)}async function ab(n){let e=Je();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 rb(e).extractAllTo(n,!0),await Au(n)}async function cb(){let n=te(),e=zt(),t=await z.promises.readdir(e);for(let r of t){let i=Jt.join(n,r);await z.promises.rm(i,{force:!0}),await z.promises.rename(Jt.join(e,r),i)}await z.promises.rm(e,{recursive:!0,force:!0}),await z.promises.rm(Jt.join(n,"orama.dpack"),{force:!0})}async function lb(n,e){e?.start("Installing documentation index\u2026"),await Ze({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await hd(n),e&&(e.text="Documentation index installed.")}async function db(n,e,t){let r=zt(),i=await Iu();await z.promises.mkdir(te(),{recursive:!0}),await z.promises.rm(r,{recursive:!0,force:!0}),t?.start("Building search index\u2026"),await Ze({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ab(i),await Du({docsDir:i,tmpDir:r,docsZipSha256:e,termsHash:ui(),synonymsHash:di(),builtBy:n.builtBy??"doc-init",onProgress:async o=>{t&&(t.text=o.message),await Ze({state:"indexing",current:o.current,total:o.total,message:o.message})}})}finally{await z.promises.rm(i,{recursive:!0,force:!0})}await Ze({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await cb(),eu()}async function Tu(n){await Ze({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),n?.succeed("Documentation ready.")}async function ub(n){let e=await rs(),t=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";n?.succeed(t),await Ze({state:"done",message:t,error:null})}async function pb(n,e){let t=n instanceof Error?n.message:String(n);throw await Ze({state:"error",error:t}),await sb(`ERROR: ${t}`),e?.fail(t),n}async function mb(){let n=te();await z.promises.mkdir(n,{recursive:!0});let e=td();return z.existsSync(e)||await z.promises.writeFile(e,"","utf-8"),e}async function hb(){let n=await mb();return ib.lock(n,{stale:1800*1e3})}async function fb(){let n=Je(),e=(n?await li(n):null)??await ns();if(!e)throw new Error("docs.zip not found");return e}async function gb(n,e){let t=await fb(),r=n.force||await os(n.force),i=await is(n.force);if(!r&&!i&&kn()){await ub(e);return}if(Xo()&&!n.force){await lb(t,e),await Tu(e);return}await db(n,t,e),await Tu(e)}var Cs=class{static async run(e={}){let t=e.background??!1,i=e.quiet??t?void 0:Ru({text:"Checking documentation\u2026",color:"cyan"}),o;try{o=await hb(),await ts(wd("Starting documentation setup\u2026")),await gb(e,i)}catch(s){return pb(s,i)}finally{o&&await o()}}};async function yb(n){for(;;){let e=await pi();if(e.state==="done"&&kn())return;if(e.state==="error")throw new Ps("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 ob(500)}}async function ku(n,e=!1){n.text=e?"Repairing documentation index\u2026":"Starting documentation setup\u2026",await Cs.run({builtBy:"doc-init",force:e,quiet:!0})}async function vb(){if(kn())return;let n=Ru({text:"Documentation is being prepared\u2026",color:"cyan"}).start();try{if(await bd()){await yb(n),n.succeed("Documentation ready.");return}if(await os()){await ku(n),n.succeed("Documentation ready.");return}await ku(n,!0),n.succeed("Documentation ready.")}catch(e){throw n.fail(e.message),e}}async function Bn(){await vb(),await xu()}var Ds=class{async search(e,t,r=20){return await Bn(),ru(e,t,r)}async readDocument(e){return await Bn(),ud(e)}},Is=new Ds;function Mu(...n){return e=>{if(!n.includes(e))throw new As(`Allowed values: ${n.join(", ")}`);return e}}function Sb(n){let e=Number(n);if(!Number.isInteger(e)||e<=0)throw new As("Must be a positive integer.");return e}var Eb=Mu("json","default"),Pb=Mu("json","default"),Ti=new wb("docs").description("Search and read HarmonyOS documentation from local docs directory");Ti.command("search <keywords...>").description("Search documentation by keywords").option("--catalog <name>","Catalog name (all for all catalogs)",Db,"all").option("--format <fmt>","Output format (default, json)",Eb,"default").option("--limit <n>","Max number of results",Sb,20).action(async(n,e)=>{try{let t=Cb(n),r=e.catalog&&e.catalog!=="all"?e.catalog:void 0,i=await Is.search(t,r,e.limit);e.format==="json"?console.log(JSON.stringify(i,null,2)):Ib(i)}catch(t){console.error(xi(t.message)),process.exit(1)}});Ti.command("read <documentId>").description("Read full content of a document by document ID").action(async n=>{try{let e=n.trim();e||(console.error(xi("Document ID cannot be empty.")),process.exit(1));let t=await Is.readDocument(e);console.log(t)}catch(e){console.error(xi(e.message)),process.exit(1)}});Ti.command("catalog").description("List all available catalogs").option("--format <fmt>","Output format (default, json)",Pb,"default").action(async n=>{try{if(await Bn(),n.format==="json"){let e=Ve.map(t=>({name:t,title:pt[t]}));console.log(JSON.stringify(e,null,2))}else for(let e of Ve)console.log(` ${e.padEnd(20)} ${bb(pt[e])}`)}catch(e){console.error(xi(e.message)),process.exit(1)}});function Cb(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>In)throw new Error(`Query exceeds ${In} characters.`);return e}function Db(n){if(n==="all")return"all";if(!Ve.includes(n))throw new As(`Invalid catalog "${n}". Allowed: all, ${Ve.join(", ")}`);return n}function Ib(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 Ou=Ti;process.env.GLOBAL_AGENT_ENVIRONMENT_VARIABLE_NAMESPACE="";Ab();X.name("devecocli").description("HarmonyOS application development command line tool").version("1.3.0-Test.5");X.addCommand(Bs);X.addCommand(Js);X.addCommand(Qs);X.addCommand(ua);X.addCommand(Na);X.addCommand(Ba);X.addCommand(mc);X.addCommand(yc);X.addCommand(Ac);X.addCommand(Nc);X.addCommand(Il);X.addCommand(Ou);var xs=process.argv.slice(2);xs.length>=2&&xs[xs.length-1]==="help"&&(process.argv=[...process.argv.slice(0,-1),"--help"]);var Tb=new Set(["update"]);X.hook("preAction",async(n,e)=>{if(process.env.DEVECO_CLI_SKIP_VERSION_CHECK)return;let t=e;for(;t.parent&&t.parent!==X;)t=t.parent;Tb.has(t.name())||await N.checkVersion()});X.parseAsync(process.argv).catch(n=>{let e=n instanceof Error?n.message:String(n??"Unknown error");console.error(xb(`Error: ${e}`)),process.exit(1)});
@@ -1,4 +1,4 @@
1
- import*as h from"fs";import*as z from"path";import Vo from"adm-zip";import Jo from"proper-lockfile";import Ko from"ora";import*as b from"fs";import*as j from"path";var ht=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],G={"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 X="1.9.1",gi=48*1024*1024,Kt=280,te=6,ee=100,ne=3,re=28,St=10,oe=/API参考|APIReference/i;var ie=6,Q=700,yt=250,xt=400,se=1320,ae=120,ce=450,ue=250,le=500,de=480,me=80,fe=200,pe=60,ge=200,he=40,Se=200,ye=200,xe=40,B=500,_e=Object.fromEntries(ht.map((t,e)=>[G[t],e])),w=Object.fromEntries(ht.map((t,e)=>[t,e]));import*as Ae from"fs";import*as m from"path";import{fileURLToPath as be}from"url";import*as W from"path";import{homedir as vn}from"os";var zn="deveco-cli";function Hn(t){let e=t.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ee(){return W.join(vn(),".local","share",zn)}function _t(){let t=process.env.DEVECO_CLI_DATA_DIR;if(t===void 0||t==="")return Ee();let e=Hn(t);return e?W.resolve(e):Ee()}var jn="docs";function q(){return m.join(_t(),jn)}function x(){return m.join(q(),".index")}function Te(){return m.join(x(),"build.lock")}function Et(){return m.join(x(),"build-status.json")}function Y(){return m.join(x(),"build-meta.json")}function V(){return m.join(x(),"search.db")}function M(){return m.join(x(),".tmp")}function Zn(){return m.join(_t(),"logs")}function At(){return m.join(Zn(),"doc-init.log")}function Un(t,e){let n=e;for(;!n.endsWith(`${m.sep}dist`)&&n!==m.dirname(n);)n=m.dirname(n);return n}function Ie(t,e){return m.dirname(Un(t,e))}function $n(){let t=be(import.meta.url),e=m.dirname(t);return t.includes(`${m.sep}dist${m.sep}`)?Ie(t,e):m.join(e,"..","..","..")}function Gn(...t){let e=be(import.meta.url),n=m.dirname(e);return e.includes(`${m.sep}dist${m.sep}`)?[m.join(Ie(e,n),...t)]:[m.join(n,"..","..","..",...t)]}function De(...t){for(let e of Gn(...t))if(Ae.existsSync(e))return e;return null}function L(){return De("docs.zip")}function bt(){return De("index.zip")}function we(){return m.join($n(),"index","data")}import*as D from"fs";import*as O from"path";var P=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Tt=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var It=null;function Dt(t){It=t}function Ce(){if(It)return It;let t=x();if(P.every(o=>D.existsSync(O.join(t,o))))return t;let n=we();if(P.every(o=>D.existsSync(O.join(n,o))))return n;throw new Tt("Lexicon files not found. Install the documentation index first (index.zip).")}function H(t){let e=O.join(Ce(),t);return D.readFileSync(e,"utf-8")}function Re(t,e){return D.readFileSync(O.join(e,t),"utf-8")}async function Ne(t,e=Ce()){await D.promises.mkdir(t,{recursive:!0});for(let n of P){let r=O.join(e,n),o=O.join(t,n);await D.promises.copyFile(r,o)}}import*as wt from"fs";import*as Xn from"yauzl";function Ct(){let t=L();return t!==null&&wt.existsSync(t)}import*as S from"fs";import*as C from"path";import Le from"adm-zip";var Oe=["search.db","build-meta.json",...P],Qn=["corpus.json","corpus-offsets.json","orama.dpack"];async function Wn(t){for(let e of Qn)await S.promises.rm(C.join(t,e),{force:!0})}async function qn(t){let e=await S.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await S.promises.rm(C.join(t,n.name),{recursive:!0,force:!0})}function Yn(t){let n=new Le(t).getEntry("build-meta.json");if(!n)throw new Error("index.zip is missing build-meta.json");return JSON.parse(n.getData().toString("utf-8"))}async function Vn(t){let e=x();await S.promises.mkdir(e,{recursive:!0});for(let n of Oe){let r=C.join(e,n);await S.promises.rm(r,{force:!0}),await S.promises.rename(C.join(t,n),r)}await Wn(e),await S.promises.rm(M(),{recursive:!0,force:!0})}function Rt(){let t=bt();return t!==null&&S.existsSync(t)}async function Pe(t){let e=bt();if(!e)throw new Error("index.zip not found");let n=Yn(e);if(n.docsZipSha256!==t)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(n.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=M();await S.promises.rm(r,{recursive:!0,force:!0}),await S.promises.mkdir(r,{recursive:!0});let o=new Le(e);for(let s of Oe){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await S.promises.writeFile(C.join(r,s),a.getData())}let i=JSON.parse(await S.promises.readFile(C.join(r,"build-meta.json"),"utf-8"));if(!S.existsSync(C.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Vn(r),await S.promises.mkdir(q(),{recursive:!0}),await qn(q()),i}import{createHash as Be}from"crypto";import*as Me from"fs";async function J(t){return new Promise((e,n)=>{let r=Be("sha256"),o=Me.createReadStream(t);o.on("data",i=>r.update(i)),o.on("error",n),o.on("end",()=>e(r.digest("hex")))})}function ke(t){return Be("sha256").update(t,"utf8").digest("hex")}function Fe(t,e){let n=e?Re(t,e):H(t);return ke(n)}function K(t){return Fe("harmonyos-synonyms.json",t)}function tt(t){return Fe("harmonyos-terms.txt",t)}var Jn={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ve(){try{let t=await b.promises.readFile(Et(),"utf-8");return JSON.parse(t)}catch{return{...Jn}}}async function Nt(t){let e=Et();await b.promises.mkdir(j.dirname(e),{recursive:!0}),await b.promises.writeFile(e,JSON.stringify(t,null,2))}function ze(t){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:t,startedAt:e,updatedAt:e,error:null}}async function R(t){let n={...await ve(),...t,updatedAt:Date.now()};return await Nt(n),n}async function Lt(){let t=L();return t?J(t):null}async function Ot(){try{let t=await b.promises.readFile(Y(),"utf-8");return JSON.parse(t)}catch{return null}}async function Pt(t=!1){if(t)return"no-index";let e=await Ot();if(!e||e.segmentCount===0)return"no-index";let n=await Lt();return n&&e.docsZipSha256!==n?"docs-changed":e.indexVersion!==X?"engine-upgraded":e.termsHash!==tt()?"terms-changed":e.synonymsHash!==K()?"synonyms-changed":null}function Bt(){if(!Ct()||!b.existsSync(V())||!b.existsSync(Y()))return!1;let t=j.dirname(V());if(!P.every(e=>b.existsSync(j.join(t,e))))return!1;try{let e=b.readFileSync(Y(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function He(t=!1){return t?!0:Ct()?Bt()?await Pt()!==null:!0:!1}import*as y from"fs";import*as On from"os";import*as _ from"path";var je=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]);var Ze=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Ue=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var Kn=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,tr=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,er=/[A-Z][a-zA-Z0-9]{2,}/g,nr=/@[A-Z][a-zA-Z0-9]*/g,rr=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,$e=6,or=/^[a-z][a-z0-9]{2,}$/,ir=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,sr=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,ar=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,cr=/^[A-Z][a-zA-Z0-9]+$/;function Mt(t){return sr.test(t)}function ur(t){return ar.test(t)&&t.length>=$e}function lr(t){return cr.test(t)}function kt(t){return Mt(t)||ur(t)||lr(t)}function dr(t){let e=t.trim().toLowerCase();return Ue.has(e)?!1:je.has(e)}function mr(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function et(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function Ft(t){return[...t.matchAll(Kn)].map(e=>e[0])}function vt(t,e=$e){let n=[];for(let r of t.matchAll(tr))r[0].length>=e&&n.push(r[0]);return n}function k(t){return t.filter(e=>{let n=e.toLowerCase();return!t.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>n.length&&o.endsWith(n)&&n.length>=4})})}function T(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function fr(t){let e=new Set;T(e,t);let n=et(t);return n&&T(e,n),k([...e])}function zt(t){if(Mt(t))return fr(t);let e=new Set;return T(e,t),k([...e])}function Ht(t){let e=t.trim();if(/[A-Z]/.test(e))return null;let n=e.match(ir);if(!n)return null;let r=n[1].toLowerCase(),o=n[2].toLowerCase();if(!or.test(r)||Ze.has(r)||!dr(o))return null;let i=mr(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Ge(t){let e=Ht(t.trim());return!e||e.second!=="manager"?null:e}function jt(t,e,n){let r=n.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${n}`,"i");for(let i of[t,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function Xe(t){let e=t.trim();if(kt(e))return zt(e);let n=new Set;for(let r of Ft(t)){T(n,r);let o=et(r);o&&T(n,o)}for(let r of vt(t))T(n,r);for(let r of t.matchAll(nr))n.add(r[0]);for(let r of t.matchAll(rr))n.add(r[0]);for(let r of t.matchAll(er))r[0].length>=4&&n.add(r[0]);return k([...n])}function Qe(t){let e=t.trim();if(kt(e))return zt(e);let n=new Set,r=Ht(e);r&&T(n,r.camelCase);for(let o of Xe(e))n.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&n.add(i)}return k([...n])}var I={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function qe(t){return I.pureApiSymbol.test(t.trim())}function We(t){let e=t.trim();return I.stageModelExact.test(e)||I.stageModelEnglishExact.test(e)}var pr=[{matches:t=>I.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>We(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!We(t)&&I.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>I.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>I.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>I.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>I.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>I.routerRoute.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:t=>I.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function gr(t,e){for(let{catalog:n,multiplier:r}of e){let o=w[n];t.set(o,(t.get(o)??1)*r)}}function Ye(t,e){for(let n of pr)n.matches(t)&&gr(e,n.weights)}import{Jieba as hr}from"@node-rs/jieba";import{dict as Sr}from"@node-rs/jieba/dict.js";var nt=null,Zt=null,Ut=null;function yr(){if(nt)return nt;let t=H("harmonyos-stopwords.txt");return nt=new Set(t.split(`
1
+ import*as h from"fs";import*as z from"path";import Vo from"adm-zip";import Jo from"proper-lockfile";import Ko from"ora";import*as b from"fs";import*as j from"path";var ht=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],G={"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 X="1.9.1",gi=100*1024*1024,Kt=280,te=6,ee=100,ne=3,re=28,St=10,oe=/API参考|APIReference/i;var ie=6,Q=700,yt=250,xt=400,se=1320,ae=120,ce=450,ue=250,le=500,de=480,me=80,fe=200,pe=60,ge=200,he=40,Se=200,ye=200,xe=40,B=500,_e=Object.fromEntries(ht.map((t,e)=>[G[t],e])),w=Object.fromEntries(ht.map((t,e)=>[t,e]));import*as Ae from"fs";import*as m from"path";import{fileURLToPath as be}from"url";import*as W from"path";import{homedir as vn}from"os";var zn="deveco-cli";function Hn(t){let e=t.trim();return(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))&&(e=e.slice(1,-1).trim()),e}function Ee(){return W.join(vn(),".local","share",zn)}function _t(){let t=process.env.DEVECO_CLI_DATA_DIR;if(t===void 0||t==="")return Ee();let e=Hn(t);return e?W.resolve(e):Ee()}var jn="docs";function q(){return m.join(_t(),jn)}function x(){return m.join(q(),".index")}function Te(){return m.join(x(),"build.lock")}function Et(){return m.join(x(),"build-status.json")}function Y(){return m.join(x(),"build-meta.json")}function V(){return m.join(x(),"search.db")}function M(){return m.join(x(),".tmp")}function Zn(){return m.join(_t(),"logs")}function At(){return m.join(Zn(),"doc-init.log")}function Un(t,e){let n=e;for(;!n.endsWith(`${m.sep}dist`)&&n!==m.dirname(n);)n=m.dirname(n);return n}function Ie(t,e){return m.dirname(Un(t,e))}function $n(){let t=be(import.meta.url),e=m.dirname(t);return t.includes(`${m.sep}dist${m.sep}`)?Ie(t,e):m.join(e,"..","..","..")}function Gn(...t){let e=be(import.meta.url),n=m.dirname(e);return e.includes(`${m.sep}dist${m.sep}`)?[m.join(Ie(e,n),...t)]:[m.join(n,"..","..","..",...t)]}function De(...t){for(let e of Gn(...t))if(Ae.existsSync(e))return e;return null}function L(){return De("docs.zip")}function bt(){return De("index.zip")}function we(){return m.join($n(),"index","data")}import*as D from"fs";import*as O from"path";var P=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],Tt=class extends Error{constructor(e){super(e),this.name="LexiconNotFoundError"}};var It=null;function Dt(t){It=t}function Ce(){if(It)return It;let t=x();if(P.every(o=>D.existsSync(O.join(t,o))))return t;let n=we();if(P.every(o=>D.existsSync(O.join(n,o))))return n;throw new Tt("Lexicon files not found. Install the documentation index first (index.zip).")}function H(t){let e=O.join(Ce(),t);return D.readFileSync(e,"utf-8")}function Re(t,e){return D.readFileSync(O.join(e,t),"utf-8")}async function Ne(t,e=Ce()){await D.promises.mkdir(t,{recursive:!0});for(let n of P){let r=O.join(e,n),o=O.join(t,n);await D.promises.copyFile(r,o)}}import*as wt from"fs";import*as Xn from"yauzl";function Ct(){let t=L();return t!==null&&wt.existsSync(t)}import*as S from"fs";import*as C from"path";import Le from"adm-zip";var Oe=["search.db","build-meta.json",...P],Qn=["corpus.json","corpus-offsets.json","orama.dpack"];async function Wn(t){for(let e of Qn)await S.promises.rm(C.join(t,e),{force:!0})}async function qn(t){let e=await S.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await S.promises.rm(C.join(t,n.name),{recursive:!0,force:!0})}function Yn(t){let n=new Le(t).getEntry("build-meta.json");if(!n)throw new Error("index.zip is missing build-meta.json");return JSON.parse(n.getData().toString("utf-8"))}async function Vn(t){let e=x();await S.promises.mkdir(e,{recursive:!0});for(let n of Oe){let r=C.join(e,n);await S.promises.rm(r,{force:!0}),await S.promises.rename(C.join(t,n),r)}await Wn(e),await S.promises.rm(M(),{recursive:!0,force:!0})}function Rt(){let t=bt();return t!==null&&S.existsSync(t)}async function Pe(t){let e=bt();if(!e)throw new Error("index.zip not found");let n=Yn(e);if(n.docsZipSha256!==t)throw new Error("Bundled index.zip does not match docs.zip. Rebuild index.zip with npm run build:index.");if(n.segmentCount<=0)throw new Error("Bundled index.zip is empty");let r=M();await S.promises.rm(r,{recursive:!0,force:!0}),await S.promises.mkdir(r,{recursive:!0});let o=new Le(e);for(let s of Oe){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await S.promises.writeFile(C.join(r,s),a.getData())}let i=JSON.parse(await S.promises.readFile(C.join(r,"build-meta.json"),"utf-8"));if(!S.existsSync(C.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await Vn(r),await S.promises.mkdir(q(),{recursive:!0}),await qn(q()),i}import{createHash as Be}from"crypto";import*as Me from"fs";async function J(t){return new Promise((e,n)=>{let r=Be("sha256"),o=Me.createReadStream(t);o.on("data",i=>r.update(i)),o.on("error",n),o.on("end",()=>e(r.digest("hex")))})}function ke(t){return Be("sha256").update(t,"utf8").digest("hex")}function Fe(t,e){let n=e?Re(t,e):H(t);return ke(n)}function K(t){return Fe("harmonyos-synonyms.json",t)}function tt(t){return Fe("harmonyos-terms.txt",t)}var Jn={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function ve(){try{let t=await b.promises.readFile(Et(),"utf-8");return JSON.parse(t)}catch{return{...Jn}}}async function Nt(t){let e=Et();await b.promises.mkdir(j.dirname(e),{recursive:!0}),await b.promises.writeFile(e,JSON.stringify(t,null,2))}function ze(t){let e=Date.now();return{state:"extracting",phase:1,phaseLabel:"Extracting documentation",current:0,total:0,message:t,startedAt:e,updatedAt:e,error:null}}async function R(t){let n={...await ve(),...t,updatedAt:Date.now()};return await Nt(n),n}async function Lt(){let t=L();return t?J(t):null}async function Ot(){try{let t=await b.promises.readFile(Y(),"utf-8");return JSON.parse(t)}catch{return null}}async function Pt(t=!1){if(t)return"no-index";let e=await Ot();if(!e||e.segmentCount===0)return"no-index";let n=await Lt();return n&&e.docsZipSha256!==n?"docs-changed":e.indexVersion!==X?"engine-upgraded":e.termsHash!==tt()?"terms-changed":e.synonymsHash!==K()?"synonyms-changed":null}function Bt(){if(!Ct()||!b.existsSync(V())||!b.existsSync(Y()))return!1;let t=j.dirname(V());if(!P.every(e=>b.existsSync(j.join(t,e))))return!1;try{let e=b.readFileSync(Y(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function He(t=!1){return t?!0:Ct()?Bt()?await Pt()!==null:!0:!1}import*as y from"fs";import*as On from"os";import*as _ from"path";var je=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]);var Ze=new Set(["a","an","and","api","app","application","arkts","arkui","for","get","harmonyos","how","in","oh","ohos","on","or","set","the","to","use","using","what","when","where","which","with","without","data","file","main","model","name","network","stage","system","type","user"]),Ue=new Set(["ability","extension","module","service","context","options","config","info","event","code","state","type","data","request","response","client","server","handler","helper","utils","factory","builder","listener","callback","observer","provider","consumer","delegate","adapter","driver","buffer","stream","channel","session","task","worker","controller","component","container","attribute","descriptor","modifier","validator","parser","formatter","encoder","decoder","filter","converter","generator","iterator","dispatcher","resolver","scanner","tracker","monitor","scheduler","renderer","loader","subscriber","proxy","button","surface","stack","heap","map","set","array","list"]);var Kn=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,tr=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,er=/[A-Z][a-zA-Z0-9]{2,}/g,nr=/@[A-Z][a-zA-Z0-9]*/g,rr=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,$e=6,or=/^[a-z][a-z0-9]{2,}$/,ir=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,sr=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,ar=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,cr=/^[A-Z][a-zA-Z0-9]+$/;function Mt(t){return sr.test(t)}function ur(t){return ar.test(t)&&t.length>=$e}function lr(t){return cr.test(t)}function kt(t){return Mt(t)||ur(t)||lr(t)}function dr(t){let e=t.trim().toLowerCase();return Ue.has(e)?!1:je.has(e)}function mr(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function et(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function Ft(t){return[...t.matchAll(Kn)].map(e=>e[0])}function vt(t,e=$e){let n=[];for(let r of t.matchAll(tr))r[0].length>=e&&n.push(r[0]);return n}function k(t){return t.filter(e=>{let n=e.toLowerCase();return!t.some(r=>{if(r===e)return!1;let o=r.toLowerCase();return o.length>n.length&&o.endsWith(n)&&n.length>=4})})}function T(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function fr(t){let e=new Set;T(e,t);let n=et(t);return n&&T(e,n),k([...e])}function zt(t){if(Mt(t))return fr(t);let e=new Set;return T(e,t),k([...e])}function Ht(t){let e=t.trim();if(/[A-Z]/.test(e))return null;let n=e.match(ir);if(!n)return null;let r=n[1].toLowerCase(),o=n[2].toLowerCase();if(!or.test(r)||Ze.has(r)||!dr(o))return null;let i=mr(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function Ge(t){let e=Ht(t.trim());return!e||e.second!=="manager"?null:e}function jt(t,e,n){let r=n.toLowerCase(),o=new RegExp(`@ohos\\.[^\\s(]*${n}`,"i");for(let i of[t,e])if(i&&(i.toLowerCase().includes(r)||o.test(i)))return!0;return!1}function Xe(t){let e=t.trim();if(kt(e))return zt(e);let n=new Set;for(let r of Ft(t)){T(n,r);let o=et(r);o&&T(n,o)}for(let r of vt(t))T(n,r);for(let r of t.matchAll(nr))n.add(r[0]);for(let r of t.matchAll(rr))n.add(r[0]);for(let r of t.matchAll(er))r[0].length>=4&&n.add(r[0]);return k([...n])}function Qe(t){let e=t.trim();if(kt(e))return zt(e);let n=new Set,r=Ht(e);r&&T(n,r.camelCase);for(let o of Xe(e))n.add(o);for(let o of e.matchAll(/\b[a-z][a-zA-Z0-9]{3,}\b/g)){let i=o[0];i!==i.toLowerCase()&&n.add(i)}return k([...n])}var I={pureApiSymbol:/^[A-Z][a-zA-Z0-9]+$/,stageModelExact:/^Stage\s*模型$/i,stageModelEnglishExact:/^stage\s+model$/i,stageModel:/Stage\s*模型/i,stageModelEntryPage:/Stage\s*模型.*EntryAbility.*(页面|新页面)/,declarePermissionBoost:/声明.*权限|应用权限.*声明|如何声明应用权限/,declarePermissionCatalog:/如何声明应用权限/,declarePermissionTokens:/如何声明应用权限|声明应用权限/,uiAbilityLifecycleBoost:/UIAbility.*生命周期|生命周期.*UIAbility|UIAblity/i,uiAbilityLifecycleCatalog:/UIAblity.*生命周期|UIAbility.*生命周期/i,entryAbilityPage:/EntryAbility.*(页面|启动|跳转|新页面)/,stateDecoratorBoost:/@State|@Prop|@Link|@Provide|@Consume/,stateDecoratorCatalog:/@State\s*装饰器|@Prop\s*装饰器|@Link\s*装饰器/,stateManagement:/状态管理原理/,routerRoute:/Router\s+路由/,dialogPopupExact:/^Dialog\s+弹窗$/,dialogPopupBoost:/Dialog\s+弹窗/};function qe(t){return I.pureApiSymbol.test(t.trim())}function We(t){let e=t.trim();return I.stageModelExact.test(e)||I.stageModelEnglishExact.test(e)}var pr=[{matches:t=>I.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>We(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!We(t)&&I.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>I.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>I.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>I.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>I.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>I.routerRoute.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:1.4},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]},{matches:t=>I.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function gr(t,e){for(let{catalog:n,multiplier:r}of e){let o=w[n];t.set(o,(t.get(o)??1)*r)}}function Ye(t,e){for(let n of pr)n.matches(t)&&gr(e,n.weights)}import{Jieba as hr}from"@node-rs/jieba";import{dict as Sr}from"@node-rs/jieba/dict.js";var nt=null,Zt=null,Ut=null;function yr(){if(nt)return nt;let t=H("harmonyos-stopwords.txt");return nt=new Set(t.split(`
2
2
  `).map(e=>e.trim()).filter(Boolean)),nt}function xr(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n]?.trim();if(!r)continue;let o=t[n+1]?.trim();if(r==="@"&&o&&/^[A-Z][a-zA-Z0-9]*$/.test(o)){e.push(`@${o}`),n+=1;continue}e.push(r)}return e}function _r(t){let e=yr(),n=[];for(let r of xr(t)){let o=r.trim();!o||e.has(o)||(n.push(o.toLowerCase()),/[A-Z]/.test(o)&&/[a-zA-Z]/.test(o)&&n.push(o))}return n}async function Er(){let t=hr.withDict(Sr),e=H("harmonyos-terms.txt");return t.loadDict(Buffer.from(e,"utf-8")),t}async function F(){return Zt||(Ut||(Ut=Er().then(t=>(Zt=t,t))),Ut)}async function Ar(t){let e=await F();return _r(e.cutForSearch(t,!0))}async function rt(t,e){let n=t.trim();if(!n||e<=0)return"";let r=(await Ar(n)).join(" ");return r.length<=e?r:r.slice(0,e)}async function br(t,e){let n=[];for(let o of t){let i=o.trim();i&&(n.push(i.toLowerCase()),/[A-Z]/.test(i)&&n.push(i))}let r=[...new Set(n)].join(" ");return r.length<=e?r:r.slice(0,e)}async function ot(t){let e=!!t.sectionTitle.trim(),n=t.titleTokens.trim(),r=e?de:se,o=e?fe:ce,i=e?await br(t.apiSymbols,o):await rt(t.apiSymbols.join(" "),o),a=(await Promise.all([rt(n,e?me:ae),Promise.resolve(i),rt(t.headingsText,e?pe:ue),rt(t.bodySample,e?ge:le)])).filter(Boolean).join(" ");return a.length<=r?a:a.slice(0,r)}var Ve=["harmonyos-releases","harmonyos-roadmap"],Tr=new Set(Ve.map(t=>w[t])),ks=Ve.map(t=>`${G[t]}/`);function Ir(t){return Tr.has(t)}function Je(t){let e=[],n=[];for(let r of t)Ir(r.catalog_id)?n.push(r):e.push(r);return[...e,...n]}var Dr=[{pattern:/@ohos\./i,catalog:"harmonyos-references",multiplier:1.5},{pattern:/@[A-Z][a-zA-Z]+/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(如何|怎么|怎样|步骤)/,catalog:"harmonyos-guides",multiplier:1.45},{pattern:/(生命周期|原理|概述|什么是|模型|介绍)/,catalog:"harmonyos-guides",multiplier:1.35},{pattern:/(报错|失败|错误|异常|排查)/,catalog:"harmonyos-guides",multiplier:1.25},{pattern:/(报错|失败|FAQ)/i,catalog:"harmonyos-faqs",multiplier:1.2},{pattern:/(构建|签名|打包|发布|上架|应用市场|hvigor|ohpm)/i,catalog:"harmonyos-guides",multiplier:1.3},{pattern:/(行为变更|changelog|升级|适配|版本说明)/i,catalog:"harmonyos-releases",multiplier:1.3},{pattern:/(路由|弹窗|手势|页面|权限|装饰器)/,catalog:"harmonyos-guides",multiplier:1.25,skipForPureApiSymbol:!0}];function Z(t,e,n){let r=w[e];t.set(r,(t.get(r)??1)*n)}function wr(t,e){let n=t.trim(),r=/[\u4e00-\u9fff]/.test(n),o=/\b[A-Z][a-zA-Z0-9]{2,}\b/.test(n),i=/\b[a-z][a-zA-Z0-9]{3,}\b/.test(n);if(r&&(o||i)){Z(e,"harmonyos-guides",1.45),Z(e,"harmonyos-references",1.35);return}(o||i)&&Z(e,"harmonyos-references",1.55),/\b[A-Z][a-zA-Z]*(Gesture|Dialog|Sheet|Transition|Recognizer)\b/.test(n)&&Z(e,"harmonyos-references",1.75)}function Ke(t){let e=new Map,n=t.trim();if(!n)return e;let r=qe(n);wr(n,e),Ye(n,e);for(let o of Dr)o.pattern.test(n)&&(o.skipForPureApiSymbol&&r||Z(e,o.catalog,o.multiplier));return e}function it(t){process.env.DEVECO_CLI_DEBUG&&console.log(`[DEBUG] ${t}`)}var Cr=[" ","\u3002","\uFF0C","\uFF1B","\u3001",".","!","?"];function tn(t,e){let n=-1;for(let r of Cr){let o=t.lastIndexOf(r);o>n&&(n=o)}return n>=e?n:-1}function en(t,e){let n=t.trim();if(n.length<=e)return{text:n,excerptTruncated:!1};let r=n.slice(0,e),o=tn(r,e-20),i=o>=0?o:e;return{text:n.slice(0,i).trimEnd(),excerptTruncated:!0}}function nn(t,e,n={}){let{maxLen:r=ye,contextChars:o=xe,excerptTruncated:i=!1}=n,s=t.replace(/\s+/g," ").trim();if(!s)return"";if(s.length<=r)return i?`${s}...`:s;let a=e.split(/\s+/).map(gt=>gt.trim()).filter(Boolean),c=0;for(let gt of a){let Jt=s.toLowerCase().indexOf(gt.toLowerCase());if(Jt>=0){c=Jt;break}}let f=Math.max(0,c-o),p=Math.min(s.length,f+r),u=s.slice(f,p),E=tn(u,r-25);E>=0&&(p=f+E);let g=s.slice(f,p).trim(),A=f>0?"...":"",Fn=p<s.length||i?"...":"";return`${A}${g}${Fn}`}var Rr=`
3
3
  SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
4
4
  d.catalog_id, bm25(segments_fts) AS bm25
package/docs.zip CHANGED
Binary file
package/index.zip CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deveco-test/deveco-cli",
3
- "version": "1.3.0-Test.3",
3
+ "version": "1.3.0-Test.5",
4
4
  "description": "HarmonyOS application development command line tool",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -45,11 +45,11 @@
45
45
  "@eslint/js": "^10.0.1",
46
46
  "@types/adm-zip": "^0.5.8",
47
47
  "@types/better-sqlite3": "^7.6.13",
48
- "@types/yauzl": "^2.10.3",
49
48
  "@types/fs-extra": "^11.0.4",
50
49
  "@types/global-agent": "^3.0.0",
51
50
  "@types/node": "^25.6.0",
52
51
  "@types/turndown": "^5.0.5",
52
+ "@types/yauzl": "^2.10.3",
53
53
  "eslint": "^10.2.1",
54
54
  "generate-license-file": "^4.2.1",
55
55
  "husky": "^9.1.7",