@deveco-test/deveco-cli 1.3.0-Test.2 → 1.3.0-Test.4
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/THIRD-PARTY-LICENSES +30 -0
- package/dist/cli.js +91 -84
- package/dist/internal/doc-init-background.js +16 -15
- package/docs.zip +0 -0
- package/index.zip +0 -0
- package/package.json +3 -1
- package/scripts/lib/cli-data-dir.mjs +44 -0
- package/scripts/lib/doc-init-log-path.mjs +3 -5
- package/scripts/postinstall.mjs +1 -3
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import*as p from"fs";import*as M from"path";import ko from"adm-zip";import Fo from"proper-lockfile";import vo from"ora";import*as A from"fs";import*as j from"path";var pt=["harmonyos-guides","harmonyos-references","best-practices","harmonyos-faqs","harmonyos-releases","harmonyos-roadmap"],$={"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 Q="1.8.0",ti=80*1024*1024,qt=280,Wt=6,Yt=100,Jt=3,Kt=28,gt=10,Vt=/API参考|APIReference/i;var te=6,X=700,ht=250,St=400,ee=1320,ne=120,re=450,oe=250,ie=500,se=480,ae=80,ce=200,ue=60,le=200,de=40,yt=120,B=500,me=Object.fromEntries(pt.map((t,e)=>[$[t],e])),D=Object.fromEntries(pt.map((t,e)=>[t,e]));import*as fe from"fs";import*as m from"path";import{homedir as pe}from"os";import{fileURLToPath as ge}from"url";var he="deveco-cli",Rn="docs";function q(){return m.join(pe(),".local","share",he,Rn)}function E(){return m.join(q(),".index")}function Se(){return m.join(E(),"build.lock")}function _t(){return m.join(E(),"build-status.json")}function W(){return m.join(E(),"build-meta.json")}function Y(){return m.join(E(),"search.db")}function k(){return m.join(E(),".tmp")}function ye(){return m.join(pe(),".local","share",he,"logs")}function Nn(t,e){let n=e;for(;!n.endsWith(`${m.sep}dist`)&&n!==m.dirname(n);)n=m.dirname(n);return n}function _e(t,e){return m.dirname(Nn(t,e))}function On(){let t=ge(import.meta.url),e=m.dirname(t);return t.includes(`${m.sep}dist${m.sep}`)?_e(t,e):m.join(e,"..","..","..")}function Ln(...t){let e=ge(import.meta.url),n=m.dirname(e);return e.includes(`${m.sep}dist${m.sep}`)?[m.join(_e(e,n),...t)]:[m.join(n,"..","..","..",...t)]}function Ee(...t){for(let e of Ln(...t))if(fe.existsSync(e))return e;return null}function O(){return Ee("docs.zip")}function Et(){return Ee("index.zip")}function xe(){return m.join(On(),"index","data")}import*as w from"fs";import*as L from"path";var P=["harmonyos-terms.txt","harmonyos-synonyms.json","harmonyos-stopwords.txt"],xt=null;function At(t){xt=t}function Ae(){if(xt)return xt;let t=E();if(P.every(o=>w.existsSync(L.join(t,o))))return t;let n=xe();if(P.every(o=>w.existsSync(L.join(n,o))))return n;throw new Error("Lexicon files not found. Install the documentation index first (index.zip).")}function H(t){let e=L.join(Ae(),t);return w.readFileSync(e,"utf-8")}function be(t,e){return w.readFileSync(L.join(e,t),"utf-8")}async function Te(t,e=Ae()){await w.promises.mkdir(t,{recursive:!0});for(let n of P){let r=L.join(e,n),o=L.join(t,n);await w.promises.copyFile(r,o)}}import*as bt from"fs";import*as Pn from"yauzl";function Tt(){let t=O();return t!==null&&bt.existsSync(t)}import*as h from"fs";import*as C from"path";import Ie from"adm-zip";var we=["search.db","build-meta.json",...P],Mn=["corpus.json","corpus-offsets.json","orama.dpack"];async function Bn(t){for(let e of Mn)await h.promises.rm(C.join(t,e),{force:!0})}async function kn(t){let e=await h.promises.readdir(t,{withFileTypes:!0});for(let n of e)n.name!==".index"&&await h.promises.rm(C.join(t,n.name),{recursive:!0,force:!0})}function Fn(t){let n=new Ie(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=E();await h.promises.mkdir(e,{recursive:!0});for(let n of we){let r=C.join(e,n);await h.promises.rm(r,{force:!0}),await h.promises.rename(C.join(t,n),r)}await Bn(e),await h.promises.rm(k(),{recursive:!0,force:!0})}function It(){let t=Et();return t!==null&&h.existsSync(t)}async function De(t){let e=Et();if(!e)throw new Error("index.zip not found");let n=Fn(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=k();await h.promises.rm(r,{recursive:!0,force:!0}),await h.promises.mkdir(r,{recursive:!0});let o=new Ie(e);for(let s of we){let a=o.getEntry(s);if(!a)throw new Error(`index.zip is missing ${s}`);await h.promises.writeFile(C.join(r,s),a.getData())}let i=JSON.parse(await h.promises.readFile(C.join(r,"build-meta.json"),"utf-8"));if(!h.existsSync(C.join(r,"search.db")))throw new Error("index.zip is missing search.db");return await vn(r),await h.promises.mkdir(q(),{recursive:!0}),await kn(q()),i}import{createHash as Ce}from"crypto";import*as Re from"fs";async function J(t){return new Promise((e,n)=>{let r=Ce("sha256"),o=Re.createReadStream(t);o.on("data",i=>r.update(i)),o.on("error",n),o.on("end",()=>e(r.digest("hex")))})}function Ne(t){return Ce("sha256").update(t,"utf8").digest("hex")}function Oe(t,e){let n=e?be(t,e):H(t);return Ne(n)}function K(t){return Oe("harmonyos-synonyms.json",t)}function V(t){return Oe("harmonyos-terms.txt",t)}var zn={state:"idle",phase:0,phaseLabel:"Idle",current:0,total:0,message:"",startedAt:0,updatedAt:0,error:null};async function Le(){try{let t=await A.promises.readFile(_t(),"utf-8");return JSON.parse(t)}catch{return{...zn}}}async function wt(t){let e=_t();await A.promises.mkdir(j.dirname(e),{recursive:!0}),await A.promises.writeFile(e,JSON.stringify(t,null,2))}function Pe(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 Le(),...t,updatedAt:Date.now()};return await wt(n),n}async function Dt(){let t=O();return t?J(t):null}async function Ct(){try{let t=await A.promises.readFile(W(),"utf-8");return JSON.parse(t)}catch{return null}}async function Rt(t=!1){if(t)return"no-index";let e=await Ct();if(!e||e.segmentCount===0)return"no-index";let n=await Dt();return n&&e.docsZipSha256!==n?"docs-changed":e.indexVersion!==Q?"engine-upgraded":e.termsHash!==V()?"terms-changed":e.synonymsHash!==K()?"synonyms-changed":null}function Nt(){if(!Tt()||!A.existsSync(Y())||!A.existsSync(W()))return!1;let t=j.dirname(Y());if(!P.every(e=>A.existsSync(j.join(t,e))))return!1;try{let e=A.readFileSync(W(),"utf-8");return JSON.parse(e).segmentCount>0}catch{return!1}}async function Me(t=!1){return t?!0:Tt()?Nt()?await Rt()!==null:!0:!1}import*as S from"fs";import*as Tn from"os";import*as _ from"path";var Be=new Set(["picker","dialog","sheet","panel","popup","menu","layout","view","gesture","animation","transition","recognizer","manager","kit"]);var ke=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"]),Fe=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 Hn=/@ohos\.[a-z][a-zA-Z0-9.]+/gi,jn=/\b[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+\b/g,Zn=/[A-Z][a-zA-Z0-9]{2,}/g,Un=/@[A-Z][a-zA-Z0-9]*/g,Gn=/[a-z][a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z0-9]+/g,ve=6,$n=/^[a-z][a-z0-9]{2,}$/,Qn=/^([a-z][a-z0-9]{2,})\s+([a-z][a-z0-9]{2,})$/,Xn=/^@ohos\.[a-z][a-zA-Z0-9.]+$/i,qn=/^[a-z][a-z0-9]*[A-Z][a-zA-Z0-9]+$/,Wn=/^[A-Z][a-zA-Z0-9]+$/;function Ot(t){return Xn.test(t)}function Yn(t){return qn.test(t)&&t.length>=ve}function Jn(t){return Wn.test(t)}function Lt(t){return Ot(t)||Yn(t)||Jn(t)}function Kn(t){let e=t.trim().toLowerCase();return Fe.has(e)?!1:Be.has(e)}function Vn(t,e){let n=e.trim().charAt(0).toUpperCase(),r=e.trim().slice(1).toLowerCase();return`${t.trim().toLowerCase()}${n}${r}`}function tt(t){let n=t.replace(/^@ohos\./i,"").split(".").filter(Boolean);return n[n.length-1]?.trim()||void 0}function Pt(t){return[...t.matchAll(Hn)].map(e=>e[0])}function Mt(t,e=ve){let n=[];for(let r of t.matchAll(jn))r[0].length>=e&&n.push(r[0]);return n}function F(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 b(t,e){let n=e.trim();if(!n)return;t.add(n);let r=n.toLowerCase();r!==n&&t.add(r)}function tr(t){let e=new Set;b(e,t);let n=tt(t);return n&&b(e,n),F([...e])}function Bt(t){if(Ot(t))return tr(t);let e=new Set;return b(e,t),F([...e])}function kt(t){let e=t.trim();if(/[A-Z]/.test(e))return null;let n=e.match(Qn);if(!n)return null;let r=n[1].toLowerCase(),o=n[2].toLowerCase();if(!$n.test(r)||ke.has(r)||!Kn(o))return null;let i=Vn(r,o);return{first:r,second:o,camelCase:i,lower:i.toLowerCase()}}function ze(t){let e=kt(t.trim());return!e||e.second!=="manager"?null:e}function Ft(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 He(t){let e=t.trim();if(Lt(e))return Bt(e);let n=new Set;for(let r of Pt(t)){b(n,r);let o=tt(r);o&&b(n,o)}for(let r of Mt(t))b(n,r);for(let r of t.matchAll(Un))n.add(r[0]);for(let r of t.matchAll(Gn))n.add(r[0]);for(let r of t.matchAll(Zn))r[0].length>=4&&n.add(r[0]);return F([...n])}function je(t){let e=t.trim();if(Lt(e))return Bt(e);let n=new Set,r=kt(e);r&&b(n,r.camelCase);for(let o of He(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 F([...n])}var T={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 Ue(t){return T.pureApiSymbol.test(t.trim())}function Ze(t){let e=t.trim();return T.stageModelExact.test(e)||T.stageModelEnglishExact.test(e)}var er=[{matches:t=>T.uiAbilityLifecycleBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.65},{catalog:"harmonyos-faqs",multiplier:.82}]},{matches:t=>Ze(t),weights:[{catalog:"harmonyos-guides",multiplier:1.85},{catalog:"harmonyos-references",multiplier:.55},{catalog:"harmonyos-faqs",multiplier:.85}]},{matches:t=>!Ze(t)&&T.stageModel.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-references",multiplier:.65}]},{matches:t=>T.entryAbilityPage.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.48}]},{matches:t=>T.declarePermissionBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"best-practices",multiplier:.68}]},{matches:t=>T.stateDecoratorBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.75},{catalog:"harmonyos-references",multiplier:.42}]},{matches:t=>T.stateManagement.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.6},{catalog:"best-practices",multiplier:.78}]},{matches:t=>T.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=>T.dialogPopupBoost.test(t),weights:[{catalog:"harmonyos-guides",multiplier:1.65},{catalog:"harmonyos-faqs",multiplier:.72},{catalog:"best-practices",multiplier:.72}]}];function nr(t,e){for(let{catalog:n,multiplier:r}of e){let o=D[n];t.set(o,(t.get(o)??1)*r)}}function Ge(t,e){for(let n of er)n.matches(t)&&nr(e,n.weights)}import{Jieba as rr}from"@node-rs/jieba";import{dict as or}from"@node-rs/jieba/dict.js";var et=null,vt=null,zt=null;function ir(){if(et)return et;let t=H("harmonyos-stopwords.txt");return et=new Set(t.split(`
|
|
2
|
-
`).map(e=>e.trim()).filter(Boolean)),
|
|
3
|
-
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text,
|
|
4
|
-
bm25(segments_fts) AS bm25
|
|
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
|
+
`).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
|
+
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
4
|
+
d.catalog_id, bm25(segments_fts) AS bm25
|
|
5
5
|
FROM segments_fts
|
|
6
6
|
JOIN segments s ON s.id = segments_fts.rowid
|
|
7
7
|
JOIN documents d ON d.id = s.doc_id
|
|
8
8
|
WHERE segments_fts MATCH ?
|
|
9
9
|
ORDER BY bm25(segments_fts)
|
|
10
10
|
LIMIT ?
|
|
11
|
-
`,
|
|
12
|
-
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text,
|
|
13
|
-
bm25(segments_fts) AS bm25
|
|
11
|
+
`,Nr=`
|
|
12
|
+
SELECT d.document_id, d.doc_title, s.section_title, s.lead_text, s.excerpt_truncated,
|
|
13
|
+
d.catalog_id, bm25(segments_fts) AS bm25
|
|
14
14
|
FROM segments_fts
|
|
15
15
|
JOIN segments s ON s.id = segments_fts.rowid
|
|
16
16
|
JOIN documents d ON d.id = s.doc_id
|
|
17
17
|
WHERE segments_fts MATCH ? AND d.catalog_id = ?
|
|
18
18
|
ORDER BY bm25(segments_fts)
|
|
19
19
|
LIMIT ?
|
|
20
|
-
`,
|
|
20
|
+
`,Lr=3.5,Or=1.4,Pr=4,Br=1.8,Mr=1.35,kr=3.5,Fr=1.8,vr=120,rn=6;function Gt(t){return t.toLowerCase().replace(/[^\p{L}\p{N}@.]+/gu,"")}function zr(t){return t.split(/[^\p{L}\p{N}@.]+/u).map(Gt).filter(e=>e.length>=2)}function Hr(t,e){return e.length>1&&e.every(n=>t.includes(n))}function jr(t){return/^[a-z0-9]{1,4}$/.test(t.trim().toLowerCase())}function Zr(t,e){return t===e?kr:t.startsWith(e)||t.includes(`@ohos.${e}`)?Fr:1}function Ur(t,e){let n=Gt(e);if(n.length<2)return 1;let r=Gt(t.doc_title);if(jr(e))return Zr(r,n);if(r.includes(n))return Pr;if(n.length>=rn&&r.includes(n.slice(0,rn)))return Br;let o=zr(e);return Hr(r,o)?Mr:1}function $r(t,e){return e<=1?t:t<0?t*e:t/e}function st(t,e,n,r){let o=t.bm25/(e.get(t.catalog_id)??1);return o=$r(o,Ur(t,n)),r&&jt(t.doc_title,t.section_title,r)&&(o/=Lr,t.catalog_id===w["harmonyos-references"]&&(o/=Or)),o}function $t(t,e,n,r){return t.reduce((o,i)=>st(i,e,n,r)<st(o,e,n,r)?i:o)}function Gr(t,e){return e.some(n=>t.section_title.includes(n)||t.doc_title.includes(n))}function Xr(t,e,n,r,o){if(o){let i=t.filter(s=>jt(s.doc_title,s.section_title,o));if(i.length>0)return $t(i,n,r,o)}if(e.length>0){let i=t.filter(s=>Gr(s,e));if(i.length>0)return $t(i,n,r,o)}return $t(t,n,r,o)}function on(t,e,n,r,o){let i=Ke(e),s=Qe(e),c=Ge(e)?.camelCase,f=new Map;for(let g of t){let A=f.get(g.document_id)??[];A.push(g),f.set(g.document_id,A)}let p=[];for(let g of f.values())p.push(Xr(g,s,i,n,c));let u=p.sort((g,A)=>st(g,i,n,c)-st(A,i,n,c));return(o?Je(u):u).slice(0,r)}function at(t,e,n,r,o,i){let s=e?w[e]:void 0,a=Math.max(n,n*ie,vr),c=s===void 0?t.all(Rr,r,a):t.all(Nr,r,s,a);return(s===void 0?on(c,i,o,n,!0):on(c,i,o,n,!1)).map(p=>({title:p.doc_title,documentId:p.document_id,sectionTitle:p.section_title||void 0,snippet:nn(p.lead_text,o,{excerptTruncated:!!p.excerpt_truncated})}))}var ct=`
|
|
21
21
|
CREATE TABLE documents (
|
|
22
22
|
id INTEGER PRIMARY KEY,
|
|
23
23
|
document_id TEXT NOT NULL UNIQUE,
|
|
@@ -30,7 +30,8 @@ CREATE TABLE segments (
|
|
|
30
30
|
doc_id INTEGER NOT NULL REFERENCES documents(id),
|
|
31
31
|
section_title TEXT NOT NULL DEFAULT '',
|
|
32
32
|
lead_text TEXT NOT NULL DEFAULT '',
|
|
33
|
-
search_text TEXT NOT NULL
|
|
33
|
+
search_text TEXT NOT NULL,
|
|
34
|
+
excerpt_truncated INTEGER NOT NULL DEFAULT 0
|
|
34
35
|
);
|
|
35
36
|
|
|
36
37
|
CREATE VIRTUAL TABLE segments_fts USING fts5(
|
|
@@ -54,11 +55,11 @@ CREATE TRIGGER segments_au AFTER UPDATE ON segments BEGIN
|
|
|
54
55
|
END;
|
|
55
56
|
|
|
56
57
|
CREATE INDEX segments_doc_id_idx ON segments(doc_id);
|
|
57
|
-
`;var
|
|
58
|
+
`;var v=null,Xt=null;function Qr(){v?.close(),v=null,Xt=null}function Wr(t,e){if(v&&Xt===e)return v;v?.close();let n=new t(e,{readonly:!0,fileMustExist:!0});return v=n,Xt=e,n.pragma("mmap_size = 268435456"),n.pragma("cache_size = -8000"),n.pragma("query_only = ON"),n}function qr(t,e){let n=new t(e);return n.pragma("journal_mode = OFF"),n.pragma("synchronous = OFF"),n.pragma("temp_store = MEMORY"),n.exec(ct),n}function Yr(t,e,n){let r=e.get(n.documentId);if(r!==void 0)return r;let i=t.prepare("SELECT id FROM documents WHERE document_id = ?").get(n.documentId);if(i)return e.set(n.documentId,i.id),i.id;let a=t.prepare(`
|
|
58
59
|
INSERT INTO documents(document_id, catalog_id, doc_title)
|
|
59
60
|
VALUES (?, ?, ?)
|
|
60
|
-
`).run(n.documentId,n.catalogId,n.docTitle),c=Number(a.lastInsertRowid);return e.set(n.documentId,c),c}async function
|
|
61
|
-
INSERT INTO segments(doc_id, section_title, lead_text, search_text)
|
|
62
|
-
VALUES (?, ?, ?, ?)
|
|
63
|
-
`),a=n.length;for(let c=0;c<a;c+=B){let f=n.slice(c,c+B),g=await Promise.all(f.map(async x=>({source:x,searchText:await rt(x)})));o.transaction(x=>{for(let y of x){let I=kr(o,i,y.source);s.run(I,y.source.sectionTitle,y.source.leadText,y.searchText)}})(g),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function vr(t,e,n,r,o,i,s){let a=Mr(t,e);return st({all(c,...f){return a.prepare(c).all(...f)}},n,r,o,i,s)}async function Je(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Pr,buildSearchIndex:(n,r,o)=>Fr(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(vr(e,i,r,o,s,a,c))}}import{readFile as zr,stat as Hr,writeFile as jr}from"fs/promises";var Ut=null,N=null;async function Gt(){return Ut||(Ut=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),Ut}function Zr(t){return{all(e,...n){let r=t.prepare(e);n.length>0&&r.bind(n);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function Ur(t){let e=await Hr(t);if(N&&N.dbPath===t&&N.mtimeMs===e.mtimeMs)return N.db;N?.db.close();let n=await Gt(),r=n.capi,o=n.wasm,i=new Uint8Array(await zr(t)),s=o.allocFromTypedArray(i),a=new n.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),N={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function Ke(){N?.db.close(),N=null}async function Gr(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText]),e.step(),e.reset()}t.exec("COMMIT")}function $r(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function Qr(t,e,n){await v();let r=await Gt(),o=new r.oo1.DB(":memory:","c");o.exec(at);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text) VALUES (?, ?, ?, ?)"),c=$r(o,i,s),f=e.length;for(let u=0;u<f;u+=B){let x=e.slice(u,u+B),y=await Promise.all(x.map(async I=>({source:I,searchText:await rt(I)})));await Gr(o,a,c,y),await n?.(Math.min(u+x.length,f),f)}o.exec("ANALYZE");let g=r.capi.sqlite3_js_db_export(o);await jr(t,g),o.close(),Ke()}async function Xr(t,e,n,r,o,i){let s=await Ur(t);return st(Zr(s),e,n,r,o,i)}async function Ve(){return await Gt(),{kind:"sqlite-wasm",resetCache:Ke,buildSearchIndex:Qr,searchIndex:(t,e,n,r,o,i,s)=>Xr(r,e,n,o,i,s)}}var ct=null,$t=null;async function qr(){try{let e=await Je();return ot("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){ot(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let t=await Ve();return ot("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),t}async function Qt(){return ct||(ct=qr().then(t=>($t=t,t))),ct}function tn(){$t?.resetCache(),ct=null,$t=null}function en(){tn()}async function nn(t,e,n){await(await Qt()).buildSearchIndex(t,e,n)}import{unified as dn}from"unified";import mn from"remark-parse";import fn from"remark-gfm";import{toString as lt}from"mdast-util-to-string";var Wr=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,Yr=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,Jr=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,Kr=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,Vr=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function ut(t){let e=t.trim(),n=e.match(Kr);return n?n[1]:e}function to(t){let e=t.match(Wr);if(!e)return;let n=ut(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function eo(t){let e=ut(t.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:t,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(t))return{displayTitle:t,symbolName:e,searchExtras:[e]}}function U(t){let e=t.trim();return e?to(e)??(()=>{let n=e.match(Yr);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(Jr);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??eo(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function no(t){if(t.length<2||t.length>36||Vr.test(t))return!1;let e=[...t.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function rn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(no(n))return n}return""}function on(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var ro=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,G=/@[A-Z][a-zA-Z]+/g,oo=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,io=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,so=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,ao=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),co=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),uo=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function pn(t,e){let n=new Set,r=[t,...e];for(let o of r){for(let i of Pt(o)){b(n,i);let s=tt(i);s&&b(n,s)}for(let i of Mt(o))b(n,i);for(let i of o.matchAll(ro)){let s=i[0];lo(s)&&n.add(s)}for(let i of o.matchAll(G))n.add(i[0])}return F([...n])}function lo(t){let e=t.trim();if(!e||G.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return uo.has(n)?!1:/^[A-Z]/.test(n)}return ao.has(e)?!1:co.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function sn(t){let e=t.trim();return!!(!e||so.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function gn(t,e){let n=e.jsonTitle?.trim(),r=go(t,"").trim(),o=e.fileName.trim();return n&&!sn(n)?n:r&&!sn(r)?r:n||r||o}function hn(t){return oo.test(t.trim())}function Xt(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=ut(e);return io.test(n)}function dt(t){let e=t.trim();return e?G.test(e)||hn(e)||Xt(e)?!0:!!U(e).symbolName:!1}function mo(t){let e=t.trim();return!(!e||hn(e)||Xt(e))}function fo(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!mo(o)||e.has(o)||(e.add(o),n.push(o))}return n}function an(t){if(!t.includes("."))return 0;let e=t.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function po(t,e){let n=an(t)-an(e);return n!==0?n:t.localeCompare(e)}function Sn(t,e=[]){let n=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(n),o=[...new Set(t.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(po),[...n,...o].slice(0,de)}function mt(t){return t.replace(/\s+/g," ").trim()}function cn(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function go(t,e=""){let n=t.split(/\r?\n/),r=0;for(;r<n.length&&!n[r].trim();)r+=1;if(r>=n.length)return e;let o=cn(n[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return cn(i[1].trim());if(r+1<n.length){let s=n[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function yn(t){let e=mt(t.join(" "));if(e.length<=X)return e;let n=e.slice(0,X);return e.length<=X+ht?n:`${n} ${e.slice(-ht)}`}function ho(t){let e=fo(t).join(" ");return e.length<=St?e:e.slice(0,St)}function _n(t){let e=mt(t);return e.length<=yt?e:e.slice(0,yt)}function En(t,e){if(t.type==="code"){e.codeBlocks.push(t.value??"");return}if("children"in t&&Array.isArray(t.children)){for(let r of t.children)En(r,e);return}let n=mt(lt(t));n&&e.bodyParts.push(n)}function So(t){let e=dn().use(mn).use(fn).parse(t),n=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&n.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=lt(a).trim();if(a.depth>=4&&c&&dt(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),En(s,r)}return o(),n.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:n}function yo(t){return Vt.test(t)}function _o(t){return t.filter(e=>e.sectionTitle&&dt(e.sectionTitle)).length}function Eo(t){return{sectionTitle:t.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:t.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:t.flatMap(e=>e.codeBlocks).slice(0,8)}}function un(t){let e=t.trim();return!e||G.test(e)?G.test(e):/对象说明$|枚举说明$/.test(e)?!0:Xt(e)}function xo(t){let e=t.filter(u=>!u.sectionTitle||!dt(u.sectionTitle)),n=t.filter(u=>u.sectionTitle&&dt(u.sectionTitle)),r=n.filter(u=>un(u.sectionTitle)),o=n.filter(u=>!un(u.sectionTitle)),i=Math.max(0,Kt-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(u=>ln(u.sectionTitle)),f=a.filter(u=>!ln(u.sectionTitle)),g=[];for(let u=0;u<f.length;u+=gt)g.push(Eo(f.slice(u,u+gt)));return[...e,...r,...s,...c,...g]}function Ao(t,e,n){let r=t.split(/\r?\n/).length,o=_o(e);return o===0?!1:yo(n)?r>=Yt&&o>=Jt:r>=qt&&o>=Wt}var bo=/^\[h2\][A-Za-z]/;function ln(t){return bo.test(t.trim())}function xn(t){if(!t.includes(" | ")){let n=U(t);return n.symbolName?[n.symbolName]:[]}let e=[];for(let n of t.split(" | ")){let r=U(n.trim()).symbolName;r&&e.push(r)}return e}function To(t,e,n,r){let o=xn(t),i=pn(n,r);return e.symbolName&&i.push(e.symbolName),Sn([...o,...i],o)}function Io(t,e){let n=yn(t.bodyParts),r=t.sectionTitle.trim(),o=U(r),i=rn(t.bodyParts),s=on(r,i,o),a=xn(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,f=[e.docTitle,s,...t.bodyParts].join(" ");return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:To(r,o,f,t.codeBlocks),bodySample:n,leadText:_n(n)}}function An(t,e){for(let n of t){if(n.type==="heading"){let o=lt(n).trim();o&&e.headings.push(o);continue}if(n.type==="code"){e.codeBlocks.push(n.value??"");continue}if("children"in n&&Array.isArray(n.children)){An(n.children,e);continue}let r=mt(lt(n));r&&e.bodyParts.push(r)}}function wo(t){let e=dn().use(mn).use(fn).parse(t),n={headings:[],bodyParts:[],codeBlocks:[]};return An(e.children,n),n}function Do(t,e){let n=wo(t),r=e.docTitle?.trim()||e.documentId,o=yn(n.bodyParts),i=[r,...n.headings,o].join(" ");return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:ho(n.headings),apiSymbols:Sn(pn(i,n.codeBlocks)),bodySample:o,leadText:_n(o)}}function bn(t,e){let n=e.docTitle?.trim()||e.documentId,r=So(t);return Ao(t,r,e.documentId)?xo(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>Io(o,{...e,docTitle:n})):[Do(t,{...e,docTitle:n})]}async function Co(t){let e=[];async function n(r){let o=await S.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}function Ro(t,e){let n=_.relative(e,t).split(_.sep).join("/").split("/");if(n[0]==="docs"&&(n=n.slice(1)),n.length<2)return null;let r=n[0],o=me[r];if(o===void 0)return null;let i=n[n.length-1].replace(/\.md$/,"");return n[n.length-1]=i,{documentId:n.join("/"),catalogId:o,docTitle:i}}async function No(t){let e=t.replace(/\.md$/,".json");try{let n=await S.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Oo(t,e){let n=Ro(t,e);if(!n)return[];let r=await S.promises.readFile(t,"utf-8"),o=gn(r,{jsonTitle:await No(t),fileName:n.docTitle});return bn(r,{...n,docTitle:o})}async function Lo(t,e,n){let r=_.join(e,"search.db");return await nn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}async function Po(t){let e=await Co(t),n=[];for(let r of e){let o=await Oo(r,t);n.push(...o)}return n}function Mo(t,e){return{indexVersion:Q,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function In(t){t.lexiconDir&&At(t.lexiconDir);try{let e=await Po(t.docsDir);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await S.promises.mkdir(t.tmpDir,{recursive:!0});let n=await Lo(e,t.tmpDir,t.onProgress),r=Mo(t,n);return await S.promises.writeFile(_.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Te(t.tmpDir),r}finally{t.lexiconDir&&At(null)}}async function wn(){return S.promises.mkdtemp(_.join(Tn.tmpdir(),"deveco-docs-"))}async function Bo(t,e){try{await S.promises.rename(t,e)}catch(n){let r=n.code;if(r!=="EPERM"&&r!=="EXDEV")throw n;await S.promises.cp(t,e,{recursive:!0}),await S.promises.rm(t,{recursive:!0,force:!0})}}async function Dn(t){let e=_.join(t,"docs");try{await S.promises.access(e)}catch{return}let n=new Set(["docs","docs.zip"]);for(let r of await S.promises.readdir(e,{withFileTypes:!0})){if(n.has(r.name))continue;let o=_.join(e,r.name),i=_.join(t,r.name);await S.promises.rm(i,{recursive:!0,force:!0}),await Bo(o,i)}await S.promises.rm(_.join(e,"docs"),{recursive:!0,force:!0}),await S.promises.rm(_.join(e,"docs.zip"),{force:!0}),await S.promises.rm(e,{recursive:!0,force:!0})}async function zo(t){let e=process.env.DEVECO_DOC_INIT_LOG??M.join(ye(),"doc-init.log");await p.promises.mkdir(M.dirname(e),{recursive:!0}),await p.promises.appendFile(e,`${new Date().toISOString()} ${t}
|
|
64
|
-
`)}async function
|
|
61
|
+
`).run(n.documentId,n.catalogId,n.docTitle),c=Number(a.lastInsertRowid);return e.set(n.documentId,c),c}async function Vr(t,e,n,r){await F();let o=qr(t,e),i=new Map,s=o.prepare(`
|
|
62
|
+
INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated)
|
|
63
|
+
VALUES (?, ?, ?, ?, ?)
|
|
64
|
+
`),a=n.length;for(let c=0;c<a;c+=B){let f=n.slice(c,c+B),p=await Promise.all(f.map(async E=>({source:E,searchText:await ot(E)})));o.transaction(E=>{for(let g of E){let A=Yr(o,i,g.source);s.run(A,g.source.sectionTitle,g.source.leadText,g.searchText,g.source.excerptTruncated?1:0)}})(p),await r?.(Math.min(c+f.length,a),a)}o.exec("ANALYZE"),o.exec("VACUUM"),o.close()}function Jr(t,e,n,r,o,i,s){let a=Wr(t,e);return at({all(c,...f){return a.prepare(c).all(...f)}},n,r,o,i,s)}async function sn(){let e=(await import("better-sqlite3")).default;return{kind:"better-sqlite3",resetCache:Qr,buildSearchIndex:(n,r,o)=>Vr(e,n,r,o),searchIndex:(n,r,o,i,s,a,c)=>Promise.resolve(Jr(e,i,r,o,s,a,c))}}import{readFile as Kr,stat as to,writeFile as eo}from"fs/promises";var Qt=null,N=null;async function Wt(){return Qt||(Qt=(async()=>{let t=(await import("@sqlite.org/sqlite-wasm")).default;return t()})()),Qt}function no(t){return{all(e,...n){let r=t.prepare(e);n.length>0&&r.bind(n);let o=[];for(;r.step();)o.push(r.get({}));return r.finalize(),o}}}async function ro(t){let e=await to(t);if(N&&N.dbPath===t&&N.mtimeMs===e.mtimeMs)return N.db;N?.db.close();let n=await Wt(),r=n.capi,o=n.wasm,i=new Uint8Array(await Kr(t)),s=o.allocFromTypedArray(i),a=new n.oo1.DB(":memory:"),c=r.SQLITE_DESERIALIZE_READONLY|r.SQLITE_DESERIALIZE_RESIZEABLE|r.SQLITE_DESERIALIZE_FREEONCLOSE;return r.sqlite3_deserialize(a.pointer,"main",s,i.byteLength,i.byteLength,c),N={dbPath:t,mtimeMs:e.mtimeMs,db:a},a}function an(){N?.db.close(),N=null}async function oo(t,e,n,r){t.exec("BEGIN");for(let o of r){let i=n(o.source);e.bind([i,o.source.sectionTitle,o.source.leadText,o.searchText,o.source.excerptTruncated?1:0]),e.step(),e.reset()}t.exec("COMMIT")}function io(t,e,n){return r=>{let o=e.get(r.documentId);if(o!==void 0)return o;let i=t.selectValue("SELECT id FROM documents WHERE document_id = ?",[r.documentId]);if(i!=null){let a=Number(i);return e.set(r.documentId,a),a}n.bind([r.documentId,r.catalogId,r.docTitle]),n.step(),n.reset();let s=Number(t.selectValue("SELECT last_insert_rowid()"));return e.set(r.documentId,s),s}}async function so(t,e,n){await F();let r=await Wt(),o=new r.oo1.DB(":memory:","c");o.exec(ct);let i=new Map,s=o.prepare("INSERT INTO documents(document_id, catalog_id, doc_title) VALUES (?, ?, ?)"),a=o.prepare("INSERT INTO segments(doc_id, section_title, lead_text, search_text, excerpt_truncated) VALUES (?, ?, ?, ?, ?)"),c=io(o,i,s),f=e.length;for(let u=0;u<f;u+=B){let E=e.slice(u,u+B),g=await Promise.all(E.map(async A=>({source:A,searchText:await ot(A)})));await oo(o,a,c,g),await n?.(Math.min(u+E.length,f),f)}o.exec("ANALYZE");let p=r.capi.sqlite3_js_db_export(o);await eo(t,p),o.close(),an()}async function ao(t,e,n,r,o,i){let s=await ro(t);return at(no(s),e,n,r,o,i)}async function cn(){return await Wt(),{kind:"sqlite-wasm",resetCache:an,buildSearchIndex:so,searchIndex:(t,e,n,r,o,i,s)=>ao(r,e,n,o,i,s)}}var ut=null,qt=null;async function co(){try{let e=await sn();return it("doc-index: using better-sqlite3 SQLite backend"),e}catch(e){it(`doc-index: better-sqlite3 unavailable (${e.message}); falling back to sqlite-wasm`)}let t=await cn();return it("doc-index: using @sqlite.org/sqlite-wasm SQLite backend"),t}async function Yt(){return ut||(ut=co().then(t=>(qt=t,t))),ut}function un(){qt?.resetCache(),ut=null,qt=null}function ln(){un()}async function dn(t,e,n){await(await Yt()).buildSearchIndex(t,e,n)}import{unified as xn}from"unified";import _n from"remark-parse";import En from"remark-gfm";import{toString as dt}from"mdast-util-to-string";var uo=/^(.+?)(\d+\+)?(对象|枚举|错误码)说明$/,lo=/^\[h2\]([A-Za-z][A-Za-z0-9]*)(\d+\+)?$/,mo=/^(.{2,20}?)\s*[((]([A-Za-z][a-zA-Z0-9]{1,40})[))]\s*$/,fo=/^([A-Za-z@][A-Za-z0-9@]*?)(\d+\+)?$/,po=/^(系统能力|元服务API|参数|返回值|说明|\*\*|表格|\|)/;function lt(t){let e=t.trim(),n=e.match(fo);return n?n[1]:e}function go(t){let e=t.match(uo);if(!e)return;let n=lt(e[1].trim());return{displayTitle:t,symbolName:n,searchExtras:[n,e[3]]}}function ho(t){let e=lt(t.replace(/\([^)]*\)$/,""));if(/^[A-Z][A-Za-z0-9]*$/.test(e))return{displayTitle:t,symbolName:e,searchExtras:[e]};if(/^[A-Z][A-Za-z0-9]*(\([^)]*\))?$/.test(t))return{displayTitle:t,symbolName:e,searchExtras:[e]}}function U(t){let e=t.trim();return e?go(e)??(()=>{let n=e.match(lo);if(n){let r=n[1];return{displayTitle:e,symbolName:r,searchExtras:[r]}}})()??(()=>{let n=e.match(mo);if(!n)return;let r=n[1].trim(),o=n[2].trim();return{displayTitle:e,symbolName:o,searchExtras:[r,o]}})()??ho(e)??{displayTitle:e,searchExtras:[]}:{displayTitle:"",searchExtras:[]}}function So(t){if(t.length<2||t.length>36||po.test(t))return!1;let e=[...t.replace(/\s/g,"")];return e.length===0?!1:e.filter(r=>new RegExp("\\p{Script=Han}","u").test(r)).length/e.length>=.4}function mn(t){for(let e of t){let n=e.trim().replace(/[。.!!??;;]+$/u,"").trim();if(So(n))return n}return""}function fn(t,e,n){let r=[t,...n.searchExtras,e].filter(Boolean);return[...new Set(r)].join(" ")}var yo=/[A-Z][a-zA-Z0-9]+(?:\.[a-zA-Z][a-zA-Z0-9]+)*/g,$=/@[A-Z][a-zA-Z]+/g,xo=/^[A-Z][A-Za-z0-9]*\.[A-Za-z][A-Za-z0-9]+/,_o=/^[A-Z][A-Za-z0-9]+(?:\([^)]*\))?$/,Eo=/^[a-z0-9]+(?:[-_][a-z0-9]+)+$/,Ao=new Set(["API","Action","Code","Connect","Connection","Context","Direction","Element","Elements","Entry","Focused","Module","Modules","Name","Names","Stage","Type","Types","Value","Values","Rect","Error"]),bo=new Set(["HAP","HSP","HAR","NAPI","CAPI","NDK","ArkTS","ArkUI","OHPM"]),To=new Set(["JSON","Object","Array","Promise","console","Math","Date","String","Number","Boolean","Error","Function","Map","Set","RegExp"]);function An(t,e){let n=new Set,r=[t,...e];for(let o of r){for(let i of Ft(o)){T(n,i);let s=et(i);s&&T(n,s)}for(let i of vt(o))T(n,i);for(let i of o.matchAll(yo)){let s=i[0];Io(s)&&n.add(s)}for(let i of o.matchAll($))n.add(i[0])}return k([...n])}function Io(t){let e=t.trim();if(!e||$.test(e))return!!e;if(e.includes(".")){let n=e.split(".")[0]??"";return To.has(n)?!1:/^[A-Z]/.test(n)}return Ao.has(e)?!1:bo.has(e)?!0:e.length<=3?!1:/^[A-Z][a-z]+[A-Z]/.test(e)?!0:e.length>=6&&/^[A-Z][A-Za-z0-9]+$/.test(e)}function pn(t){let e=t.trim();return!!(!e||Eo.test(e)||e.length>28&&!/[A-Z\u4e00-\u9fff]/.test(e)&&/^[a-z0-9_-]+$/.test(e))}function bn(t,e){let n=e.jsonTitle?.trim(),r=Ro(t,"").trim(),o=e.fileName.trim();return n&&!pn(n)?n:r&&!pn(r)?r:n||r||o}function Tn(t){return xo.test(t.trim())}function Vt(t){let e=t.trim().replace(/\([^)]*\)$/,""),n=lt(e);return _o.test(n)}function mt(t){let e=t.trim();return e?$.test(e)||Tn(e)||Vt(e)?!0:!!U(e).symbolName:!1}function Do(t){let e=t.trim();return!(!e||Tn(e)||Vt(e))}function wo(t){let e=new Set,n=[];for(let r of t){let o=r.trim();!Do(o)||e.has(o)||(e.add(o),n.push(o))}return n}function gn(t){if(!t.includes("."))return 0;let e=t.split(".").pop()??"";return/^[a-z]/.test(e)?1:2}function Co(t,e){let n=gn(t)-gn(e);return n!==0?n:t.localeCompare(e)}function In(t,e=[]){let n=[...new Set(e.map(i=>i.trim()).filter(Boolean))],r=new Set(n),o=[...new Set(t.map(i=>i.trim()).filter(Boolean))].filter(i=>!r.has(i));return o.sort(Co),[...n,...o].slice(0,he)}function ft(t){return t.replace(/\s+/g," ").trim()}function hn(t){return t.replace(/\\([\\`*_{}[\]()#+.!-])/g,"$1")}function Ro(t,e=""){let n=t.split(/\r?\n/),r=0;for(;r<n.length&&!n[r].trim();)r+=1;if(r>=n.length)return e;let o=hn(n[r].trim()),i=o.match(/^#+\s+(.+)$/);if(i)return hn(i[1].trim());if(r+1<n.length){let s=n[r+1].trim();if(/^=+$/.test(s)||/^-+$/.test(s))return o}return o||e}function Dn(t){let e=ft(t.join(" "));if(e.length<=Q)return e;let n=e.slice(0,Q);return e.length<=Q+yt?n:`${n} ${e.slice(-yt)}`}function No(t){let e=wo(t).join(" ");return e.length<=xt?e:e.slice(0,xt)}function wn(t){let e=ft(t),{text:n,excerptTruncated:r}=en(e,Se);return{leadText:n,excerptTruncated:r}}function Lo(t,e){let{leadText:n,excerptTruncated:r}=wn(t);return{leadText:n,excerptTruncated:r||!!e.trim()}}function Cn(t,e){if(t.type==="code"){e.codeBlocks.push(t.value??"");return}if("children"in t&&Array.isArray(t.children)){for(let r of t.children)Cn(r,e);return}let n=ft(dt(t));n&&e.bodyParts.push(n)}function Oo(t){let e=xn().use(_n).use(En).parse(t),n=[],r=null,o=()=>{r&&((r.sectionTitle||r.bodyParts.length||r.codeBlocks.length)&&n.push(r),r=null)},i=()=>{r||(r={sectionTitle:"",bodyParts:[],codeBlocks:[]})};for(let s of e.children){if(s.type==="heading"){let a=s,c=dt(a).trim();if(a.depth>=4&&c&&mt(c)){o(),r={sectionTitle:c,bodyParts:[],codeBlocks:[]};continue}i(),c&&r.bodyParts.push(c);continue}i(),Cn(s,r)}return o(),n.length===0?[{sectionTitle:"",bodyParts:[],codeBlocks:[]}]:n}function Po(t){return oe.test(t)}function Bo(t){return t.filter(e=>e.sectionTitle&&mt(e.sectionTitle)).length}function Mo(t){return{sectionTitle:t.map(e=>e.sectionTitle.trim()).join(" | "),bodyParts:t.flatMap(e=>e.bodyParts).slice(0,40),codeBlocks:t.flatMap(e=>e.codeBlocks).slice(0,8)}}function Sn(t){let e=t.trim();return!e||$.test(e)?$.test(e):/对象说明$|枚举说明$/.test(e)?!0:Vt(e)}function ko(t){let e=t.filter(u=>!u.sectionTitle||!mt(u.sectionTitle)),n=t.filter(u=>u.sectionTitle&&mt(u.sectionTitle)),r=n.filter(u=>Sn(u.sectionTitle)),o=n.filter(u=>!Sn(u.sectionTitle)),i=Math.max(0,re-r.length),s=o.slice(0,i),a=o.slice(i),c=a.filter(u=>yn(u.sectionTitle)),f=a.filter(u=>!yn(u.sectionTitle)),p=[];for(let u=0;u<f.length;u+=St)p.push(Mo(f.slice(u,u+St)));return[...e,...r,...s,...c,...p]}function Fo(t,e,n){let r=t.split(/\r?\n/).length,o=Bo(e);return o===0?!1:Po(n)?r>=ee&&o>=ne:r>=Kt&&o>=te}var vo=/^\[h2\][A-Za-z]/;function yn(t){return vo.test(t.trim())}function Rn(t){if(!t.includes(" | ")){let n=U(t);return n.symbolName?[n.symbolName]:[]}let e=[];for(let n of t.split(" | ")){let r=U(n.trim()).symbolName;r&&e.push(r)}return e}function zo(t,e,n,r){let o=Rn(t),i=An(n,r);return e.symbolName&&i.push(e.symbolName),In([...o,...i],o)}function Ho(t,e){let n=Dn(t.bodyParts),r=t.sectionTitle.trim(),o=U(r),i=mn(t.bodyParts),s=fn(r,i,o),a=Rn(r),c=r?a.length>0?`${e.docTitle} ${a.join(" ")}`:`${e.docTitle} ${o.symbolName??r}`:e.docTitle,f=[e.docTitle,s,...t.bodyParts].join(" "),{leadText:p,excerptTruncated:u}=Lo(n,r);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:e.docTitle,sectionTitle:r,titleTokens:c,headingsText:s,apiSymbols:zo(r,o,f,t.codeBlocks),bodySample:n,leadText:p,excerptTruncated:u}}function Nn(t,e){for(let n of t){if(n.type==="heading"){let o=dt(n).trim();o&&e.headings.push(o);continue}if(n.type==="code"){e.codeBlocks.push(n.value??"");continue}if("children"in n&&Array.isArray(n.children)){Nn(n.children,e);continue}let r=ft(dt(n));r&&e.bodyParts.push(r)}}function jo(t){let e=xn().use(_n).use(En).parse(t),n={headings:[],bodyParts:[],codeBlocks:[]};return Nn(e.children,n),n}function Zo(t,e){let n=jo(t),r=e.docTitle?.trim()||e.documentId,o=Dn(n.bodyParts),i=[r,...n.headings,o].join(" "),{leadText:s,excerptTruncated:a}=wn(o);return{documentId:e.documentId,catalogId:e.catalogId,docTitle:r,sectionTitle:"",titleTokens:r,headingsText:No(n.headings),apiSymbols:In(An(i,n.codeBlocks)),bodySample:o,leadText:s,excerptTruncated:a}}function Ln(t,e){let n=e.docTitle?.trim()||e.documentId,r=Oo(t);return Fo(t,r,e.documentId)?ko(r).filter(o=>o.sectionTitle||o.bodyParts.length>0||o.codeBlocks.length>0).map(o=>Ho(o,{...e,docTitle:n})):[Zo(t,{...e,docTitle:n})]}async function Uo(t){let e=[];async function n(r){let o=await y.promises.readdir(r,{withFileTypes:!0});for(let i of o){if(i.name.startsWith("."))continue;let s=_.join(r,i.name);i.isDirectory()?await n(s):i.isFile()&&i.name.endsWith(".md")&&e.push(s)}}return await n(t),e}function $o(t,e){let n=_.relative(e,t).split(_.sep).join("/").split("/");if(n[0]==="docs"&&(n=n.slice(1)),n.length<2)return null;let r=n[0],o=_e[r];if(o===void 0)return null;let i=n[n.length-1].replace(/\.md$/,"");return n[n.length-1]=i,{documentId:n.join("/"),catalogId:o,docTitle:i}}async function Go(t){let e=t.replace(/\.md$/,".json");try{let n=await y.promises.readFile(e,"utf-8");return JSON.parse(n).title?.trim()||void 0}catch{return}}async function Xo(t,e){let n=$o(t,e);if(!n)return[];let r=await y.promises.readFile(t,"utf-8"),o=bn(r,{jsonTitle:await Go(t),fileName:n.docTitle});return Ln(r,{...n,docTitle:o})}async function Qo(t,e,n){let r=_.join(e,"search.db");return await dn(r,t,async(o,i)=>{await n?.({current:o,total:i,message:`Building search index\u2026 ${o.toLocaleString()} / ${i.toLocaleString()} segments`})}),t.length}async function Wo(t){let e=await Uo(t),n=[];for(let r of e){let o=await Xo(r,t);n.push(...o)}return n}function qo(t,e){return{indexVersion:X,docsZipSha256:t.docsZipSha256,termsHash:t.termsHash,synonymsHash:t.synonymsHash,segmentCount:e,builtAt:Date.now(),builtBy:t.builtBy}}async function Pn(t){t.lexiconDir&&Dt(t.lexiconDir);try{let e=await Wo(t.docsDir);await t.onProgress?.({current:0,total:e.length,message:`Building search index\u2026 0 / ${e.length.toLocaleString()} segments`}),await y.promises.mkdir(t.tmpDir,{recursive:!0});let n=await Qo(e,t.tmpDir,t.onProgress),r=qo(t,n);return await y.promises.writeFile(_.join(t.tmpDir,"build-meta.json"),JSON.stringify(r,null,2)),await Ne(t.tmpDir),r}finally{t.lexiconDir&&Dt(null)}}async function Bn(){return y.promises.mkdtemp(_.join(On.tmpdir(),"deveco-docs-"))}async function Yo(t,e){try{await y.promises.rename(t,e)}catch(n){let r=n.code;if(r!=="EPERM"&&r!=="EXDEV")throw n;await y.promises.cp(t,e,{recursive:!0}),await y.promises.rm(t,{recursive:!0,force:!0})}}async function Mn(t){let e=_.join(t,"docs");try{await y.promises.access(e)}catch{return}let n=new Set(["docs","docs.zip"]);for(let r of await y.promises.readdir(e,{withFileTypes:!0})){if(n.has(r.name))continue;let o=_.join(e,r.name),i=_.join(t,r.name);await y.promises.rm(i,{recursive:!0,force:!0}),await Yo(o,i)}await y.promises.rm(_.join(e,"docs"),{recursive:!0,force:!0}),await y.promises.rm(_.join(e,"docs.zip"),{force:!0}),await y.promises.rm(e,{recursive:!0,force:!0})}async function ti(t){let e=At();await h.promises.mkdir(z.dirname(e),{recursive:!0}),await h.promises.appendFile(e,`${new Date().toISOString()} ${t}
|
|
65
|
+
`)}async function ei(t){let e=L();if(!e)throw new Error("docs.zip not found");await h.promises.rm(t,{recursive:!0,force:!0}),await h.promises.mkdir(t,{recursive:!0}),new Vo(e).extractAllTo(t,!0),await Mn(t)}async function ni(){let t=x(),e=M(),n=await h.promises.readdir(e);for(let r of n){let o=z.join(t,r);await h.promises.rm(o,{force:!0}),await h.promises.rename(z.join(e,r),o)}await h.promises.rm(e,{recursive:!0,force:!0}),await h.promises.rm(z.join(t,"orama.dpack"),{force:!0})}async function ri(t,e){e?.start("Installing documentation index\u2026"),await R({state:"installing",phase:1,phaseLabel:"Installing index",message:"Installing documentation index\u2026"}),await Pe(t),e&&(e.text="Documentation index installed.")}async function oi(t,e,n){let r=M(),o=await Bn();await h.promises.mkdir(x(),{recursive:!0}),await h.promises.rm(r,{recursive:!0,force:!0}),n?.start("Building search index\u2026"),await R({state:"indexing",phase:2,phaseLabel:"Building search index",message:"Building search index\u2026"});try{await ei(o),await Pn({docsDir:o,tmpDir:r,docsZipSha256:e,termsHash:tt(),synonymsHash:K(),builtBy:t.builtBy??"doc-init",onProgress:async i=>{n&&(n.text=i.message),await R({state:"indexing",current:i.current,total:i.total,message:i.message})}})}finally{await h.promises.rm(o,{recursive:!0,force:!0})}await R({state:"persisting",phase:3,phaseLabel:"Persisting index",message:"Persisting index\u2026"}),await ni(),ln()}async function kn(t){await R({state:"done",phase:3,phaseLabel:"Done",message:"Documentation ready.",error:null}),t?.succeed("Documentation ready.")}async function ii(t){let e=await Ot(),n=e?`Documentation already up to date. Documents: ${e.segmentCount.toLocaleString()}`:"Documentation already up to date.";t?.succeed(n),await R({state:"done",message:n,error:null})}async function si(t,e){let n=t instanceof Error?t.message:String(t);throw await R({state:"error",error:n}),await ti(`ERROR: ${n}`),e?.fail(n),t}async function ai(){let t=x();await h.promises.mkdir(t,{recursive:!0});let e=Te();return h.existsSync(e)||await h.promises.writeFile(e,"","utf-8"),e}async function ci(){let t=await ai();return Jo.lock(t,{stale:1800*1e3})}async function ui(){let t=L(),e=(t?await J(t):null)??await Lt();if(!e)throw new Error("docs.zip not found");return e}async function li(t,e){let n=await ui(),r=t.force||await He(t.force),o=await Pt(t.force);if(!r&&!o&&Bt()){await ii(e);return}if(Rt()&&!t.force){await ri(n,e),await kn(e);return}await oi(t,n,e),await kn(e)}var pt=class{static async run(e={}){let n=e.background??!1,o=e.quiet??n?void 0:Ko({text:"Checking documentation\u2026",color:"cyan"}),i;try{i=await ci(),await Nt(ze("Starting documentation setup\u2026")),await li(e,o)}catch(s){return si(s,o)}finally{i&&await i()}}};var di=process.env.DEVECO_CLI_POSTINSTALL?"postinstall":"doc-init";pt.run({background:!0,builtBy:di}).catch(()=>{process.exit(1)});
|
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
|
+
"version": "1.3.0-Test.4",
|
|
4
4
|
"description": "HarmonyOS application development command line tool",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
"scripts/postinstall.mjs",
|
|
13
13
|
"scripts/install-better-sqlite3.mjs",
|
|
14
14
|
"scripts/lib/better-sqlite3-vendor.mjs",
|
|
15
|
+
"scripts/lib/cli-data-dir.mjs",
|
|
15
16
|
"scripts/lib/doc-init-log-path.mjs",
|
|
16
17
|
"templates",
|
|
17
18
|
"THIRD-PARTY-LICENSES",
|
|
@@ -60,6 +61,7 @@
|
|
|
60
61
|
"typescript-eslint": "^8.59.1"
|
|
61
62
|
},
|
|
62
63
|
"dependencies": {
|
|
64
|
+
"@deveco-test/deveco-cli": "file:deveco-test-deveco-cli-1.3.0-Test.4.tgz",
|
|
63
65
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
64
66
|
"@node-rs/jieba": "^2.0.1",
|
|
65
67
|
"@sqlite.org/sqlite-wasm": "^3.49.1-build4",
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright (c) 2026 Huawei Device Co., Ltd.
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*
|
|
5
|
+
* Keep in sync with src/utils/cli-data-dir.ts
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { homedir } from 'os';
|
|
9
|
+
import { join, resolve } from 'path';
|
|
10
|
+
|
|
11
|
+
const APP_NAME = 'deveco-cli';
|
|
12
|
+
|
|
13
|
+
/** Strip quotes from cmd.exe `set VAR="path"` (quotes become part of the value). */
|
|
14
|
+
function normalizeEnvDataDir(value) {
|
|
15
|
+
let normalized = value.trim();
|
|
16
|
+
if (
|
|
17
|
+
(normalized.startsWith('"') && normalized.endsWith('"')) ||
|
|
18
|
+
(normalized.startsWith("'") && normalized.endsWith("'"))
|
|
19
|
+
) {
|
|
20
|
+
normalized = normalized.slice(1, -1).trim();
|
|
21
|
+
}
|
|
22
|
+
return normalized;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isCliDataDirConfigured() {
|
|
26
|
+
const raw = process.env.DEVECO_CLI_DATA_DIR;
|
|
27
|
+
return raw !== undefined && normalizeEnvDataDir(raw) !== '';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function getDefaultCliDataDir() {
|
|
31
|
+
return join(homedir(), '.local', 'share', APP_NAME);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function getCliDataDir() {
|
|
35
|
+
const raw = process.env.DEVECO_CLI_DATA_DIR;
|
|
36
|
+
if (raw === undefined || raw === '') {
|
|
37
|
+
return getDefaultCliDataDir();
|
|
38
|
+
}
|
|
39
|
+
const envDir = normalizeEnvDataDir(raw);
|
|
40
|
+
if (!envDir) {
|
|
41
|
+
return getDefaultCliDataDir();
|
|
42
|
+
}
|
|
43
|
+
return resolve(envDir);
|
|
44
|
+
}
|
|
@@ -3,15 +3,13 @@
|
|
|
3
3
|
* SPDX-License-Identifier: MIT
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { homedir } from 'os';
|
|
7
6
|
import { join } from 'path';
|
|
8
|
-
|
|
9
|
-
const APP_NAME = 'deveco-cli';
|
|
7
|
+
import { getCliDataDir } from './cli-data-dir.mjs';
|
|
10
8
|
|
|
11
9
|
export function getDocInitLogDir() {
|
|
12
|
-
return join(
|
|
10
|
+
return join(getCliDataDir(), 'logs');
|
|
13
11
|
}
|
|
14
12
|
|
|
15
13
|
export function getDocInitLogPath() {
|
|
16
|
-
return
|
|
14
|
+
return join(getDocInitLogDir(), 'doc-init.log');
|
|
17
15
|
}
|
package/scripts/postinstall.mjs
CHANGED
|
@@ -5,14 +5,13 @@
|
|
|
5
5
|
|
|
6
6
|
import { spawn } from 'child_process';
|
|
7
7
|
import { existsSync, mkdirSync } from 'fs';
|
|
8
|
-
import {
|
|
8
|
+
import { dirname, join } from 'path';
|
|
9
9
|
import { fileURLToPath } from 'url';
|
|
10
10
|
import { ensureBetterSqlite3ForDocs } from './install-better-sqlite3.mjs';
|
|
11
11
|
import { getDocInitLogPath } from './lib/doc-init-log-path.mjs';
|
|
12
12
|
|
|
13
13
|
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
14
|
const logPath = getDocInitLogPath();
|
|
15
|
-
process.env.DEVECO_DOC_INIT_LOG = logPath;
|
|
16
15
|
mkdirSync(dirname(logPath), { recursive: true });
|
|
17
16
|
|
|
18
17
|
const nativeResult = await ensureBetterSqlite3ForDocs();
|
|
@@ -38,7 +37,6 @@ const child = spawn(
|
|
|
38
37
|
...process.env,
|
|
39
38
|
DEVECO_CLI_SKIP_VERSION_CHECK: '1',
|
|
40
39
|
DEVECO_CLI_POSTINSTALL: '1',
|
|
41
|
-
DEVECO_DOC_INIT_LOG: logPath,
|
|
42
40
|
},
|
|
43
41
|
}
|
|
44
42
|
);
|