yuque-dl 1.0.50 → 1.0.51
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/cjs/cli.js +1 -1
- package/dist/cjs/index-731e1a03.js +1 -0
- package/dist/cjs/index.js +1 -1
- package/dist/es/cli.js +1 -1
- package/dist/es/{index-7a4efc0f.js → index-094ab228.js} +1 -1
- package/dist/es/index.js +1 -1
- package/package.json +2 -2
- package/types/types/index.d.ts +3 -3
- package/dist/cjs/index-73995800.js +0 -1
package/dist/cjs/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:fs"),r=require("cac"),o=require("semver"),i=require("./index-
|
|
1
|
+
"use strict";var e=require("node:fs"),r=require("cac"),o=require("semver"),i=require("./index-731e1a03.js");require("rand-user-agent"),require("node:fs/promises"),require("cli-progress"),require("node:path"),require("log4js"),require("axios"),require("node:process"),require("ora"),require("pull-md-img"),require("markdown-toc"),require("pako"),require("node:crypto");var n="undefined"!=typeof document?document.currentScript:null;const s=r.cac("yuque-dl"),{version:t,engines:c}=JSON.parse(e.readFileSync(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:n&&n.src||new URL("cli.js",document.baseURI).href)).toString());!function(){const e=c.node;o.satisfies(process.version,e)||(i.logger.error(`✕ nodejs 版本需 ${e}, 当前版本为 ${process.version}`),process.exit(1))}(),s.command("<url>","语雀知识库url").option("-d, --dist-dir <dir>","下载的目录 eg: -d download",{default:"download"}).option("-i, --ignore-img","忽略图片不下载",{default:!1}).option("-k, --key <key>",'语雀的cookie key, 默认是 "_yuque_session", 在某些企业版本中 key 不一样').option("-t, --token <token>","语雀的cookie key 对应的值").option("--ignore-toc","默认输出toc目录,添加此参数则不输出toc目录",{default:!1}).action((async(e,r)=>{try{await i.main(e,r),process.exit(0)}catch(e){i.logger.error(e.message||"unknown exception"),process.exit(1)}})),s.help(),s.version(t);try{s.parse()}catch(e){i.logger.error(e.message||"unknown exception"),process.exit(1)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e,t,r=require("node:fs/promises"),o=require("node:path"),s=require("rand-user-agent"),n=require("log4js"),i=require("cli-progress"),a=require("axios"),c=require("node:process"),l=require("ora"),u=require("pull-md-img"),h=require("markdown-toc"),p=require("pako"),d=require("node:crypto");!function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(e||(e={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(t||(t={}));const f=new Map([[t.BOARD,"画板类型"],[t.TABLE,"数据表类型"],[t.SHEET,"表格类型"],[t.DOC,"文档类型"]]),g="_yuque_session",m="https://www.yuque.com",w="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",$=(n.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),n.getLogger("yuque-dl"));class k{constructor(e,t){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=e,this.progressFilePath=`${e}/progress.json`,this.total=t}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,$.info("根据上次数据继续断点下载")),this.bar=new i.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},i.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const t=await r.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(t)}catch(t){t&&"ENOENT"===t.code&&await r.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,t){this.curr!==this.total&&(this.curr=this.curr+1,t&&(this.progressInfo.push(e),await r.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log(""))))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(e){if(!(e<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let t=0;t<e;t++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}function y({browser:e="chrome",os:t="mac os",device:r="desktop"}){r=r.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let o=s(r,e,t);if("chrome"===e)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=s(r,e,t);if("safari"===e)for(;o.includes("Applebot");)o=s(r,e,t);return o}class b{constructor(e){this.summaryInfo=e}async genFile(){const{bookName:t,bookDesc:o,bookPath:s,uuidMap:n}=this.summaryInfo;let i=`# ${t}\n\n`;o&&(i+=`> ${o}\n\n`);let a=i;const c=[];n.forEach((t=>{const r=t.toc,o=r.parent_uuid,s=this.findTree(c,o),n={text:r.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:r.uuid,level:1,type:"link"},i=r.type.toLocaleLowerCase();i===e.TITLE||""!==r.child_uuid?(n.type="title","boolean"!=typeof s?(Array.isArray(s.children)||(s.children=[]),n.level=s.level+1,s.children.push(n)):(n.level=1,c.push(n)),i===e.DOC&&(n.link=t.path)):(n.type="link",n.link=i===e.LINK?t.toc.url:t.path,"boolean"!=typeof s?(Array.isArray(s.children)||(s.children=[]),n.level=s.level+1,s.children.push(n)):(n.level=1,c.push(n)))}));a+=this.genSummaryContent(c,"");try{await r.writeFile(`${s}/SUMMARY.md`,a)}catch(e){$.error("Generate Summary Error")}return a}genSummaryContent(t,r){for(const o of t){if(o.type===e.TITLE)if(o.link){const e=o.link?o.link.replace(/\s/g,"%20"):o.link;r+=`\n${"".padStart(o.level+1,"#")} [${o.text}](${e})\n\n`}else r+=`\n${"".padStart(o.level+1,"#")} ${o.text}\n\n`;else if(o.type===e.LINK){const e=o.link?o.link.replace(/\s/g,"%20"):o.link;r+=`- [${o.text}](${e})\n`}Array.isArray(o.children)&&(r+=this.genSummaryContent(o.children,""))}return r}findIdItem(e,t){if(e.id===t)return e;if(e.children){const r=this.findTree(e.children,t);if(r)return r}return!1}findTree(e,t){if(!t)return!1;for(const r of e){const e=this.findIdItem(r,t);if(e)return e}return!1}}function I(e){const{key:t=g,token:r}=e,o={"user-agent":y({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${t}=${r};`),o}function L(e){return{headers:I(e),beforeRedirect:t=>{t.headers={...t?.headers||{},...I(e)}}}}const v=(e,t=!0)=>{const{articleUrl:r,bookId:o,token:s,key:n,host:i=m}=e;let c=`${i}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};t&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,a.get(c,L({token:s,key:n})).then((({data:e,status:t})=>({apiUrl:c,httpStatus:t,response:e})))};function S(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const T=e=>{if(!e)return"";const t=p.inflate(e,{to:"string"}),r=JSON.parse(t);let o="";return r.forEach((e=>{const t=`## ${e.name}\n`,r=function(e){let t=Object.keys(e);t=t.filter((t=>Object.keys(e[t]).some((r=>e?.[t]?.[r]?.v))));let r=[];t.forEach((t=>{const o=e[t];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...t.map((e=>Number(e)))),s=Math.max(...r.map((e=>Number(e))));if(o<0||s<0)return"";let n="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(s+1).fill(" ").map(((e,t)=>{const r=t%i.length;return i[r]})).join(" | ");a=`| |${a}|`;let c=Array(s+2).fill("---").join(" |");c=`|${c}|`,n=`${a}\n${c}\n`;for(let t=0;t<o+1;t++){const r=[];for(let o=0;o<s+1;o++){const s=e?.[t]?.[o]?.v||null;s&&"string"==typeof s?r.push(s):s&&"object"==typeof s?"image"===s?.class&&s?.src?r.push(``):"checkbox"===s?.class?r.push(s?.value?"[x] ":"[ ] "):"link"===s?.class?r.push(`[${s?.text}](${s?.url})`):"select"===s?.class&&r.push(s?.value?.join(",")):r.push(null)}n=`${n}${`| ${t+1} | ${r.join(" | ")}|`}\n`}return n}(e.data);o=`${o}\n${t}\n${r}`})),o};function E(e,t=[]){return function(e,t){try{const{host:r,pathname:o}=new URL(e);return!t.includes(r)&&Boolean(o)}catch(e){return!1}}(e,t)?`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(e)}&sign=${function(e){const t=d.createHash("sha256");return t.update(`${w}${e}`),t.digest("hex")}(e)}`:e}async function P(e){const{articleInfo:o,progressBar:s,options:n}=e,{token:i,key:a}=n,{bookId:h,itemUrl:p,savePath:d,saveFilePath:g,uuid:m,articleUrl:w,articleTitle:$,ignoreImg:k,host:y,imageServiceDomains:b}=o,I={articleUrl:p,bookId:h,token:i,host:y,key:a},{httpStatus:L,apiUrl:S,response:P}=await v(I),U=P?.data?.type?.toLocaleLowerCase();let C="";if(U===t.SHEET){const{response:e}=await v(I,!1);try{const t=e?.data?.content,r=t?JSON.parse(t):{},o=r?.sheet;C=o?T(o):""}catch(e){const t=f.get(U);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([t.BOARD,t.TABLE].includes(U)){const e=f.get(U);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof P?.data?.sourcecode)throw new Error(`download article Error: ${S}, http status ${L}`);C=P.data.sourcecode,C=function(e){const t=/!\[(.*?)\]\((http.*?latex.*?)\)/gm,r=e.match(t);let o=e;const s=e;try{r?.forEach((e=>{t.lastIndex=0;const r=t.exec(e)?.[2]??"",{pathname:s,search:n}=new URL(r);if(!s.endsWith(".svg")&&n){const t=decodeURIComponent(n);o=o.replace(e,t.slice(1))}}))}catch(e){return s}return o}(C)}const x=function(e){if(!e)return[];const t=/!\[(.*?)\]\((.*?)\)/gm;let r=Array.from(e.match(t)||[]);return r=r.map((e=>(e=e.replace(t,"$2"),/^http.*/g.test(e)?e:""))).filter((e=>Boolean(e))),r}(C);if(x.length&&!k){const e=await v(I,!1);C=function(e,t,r){if(!r)return t;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,s=[];let n,i=!0;for(;i||Boolean(n);)if(i=!1,n=o.exec(r),n?.[1])try{const e=decodeURIComponent(n[1]),t=JSON.parse(e);s.push(t?.src||"")}catch{s.push("")}const a=new Map;return e.forEach((e=>{const{origin:r,pathname:o}=new URL(e),n=`${r}${o}`,i=s.find(((e,t)=>{const r=new RegExp(`${n}.*?`).test(e);return r&&s.splice(t,1),r}));if(i){const r=new RegExp(e,"g"),o=a.get(e)||0;let s=0;t=t.replace(r,(e=>{let t=e;return s===o&&(t=i),s+=1,t})),a.set(e,o+1)}})),t}(x,C,e.response?.data?.content??"")}const N={ignoreToc:n.ignoreToc,articleTitle:$,articleUrl:w};if(x.length&&!k){let e;s.pause(),console.log(""),"test"!==c.env.NODE_ENV&&(e=l({text:`下载 "${$}" 的图片中...`,stream:c.stdout}),e.start());let t=[],o=C;try{const e=await u.run(C,{dist:d,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:w||"",transform:e=>E(e,b)});t=e.errorInfo,o=e.data}catch(e){t=[e]}C=o;const n=()=>{e&&e.stop(),s.continue()};if(t.length>0){const e=t[0];let o="图片下载失败(失败的以远程链接保存): ";throw o=e.url?`${o}${e.error?.message} ${e.url.slice(0,20)}...`:`${o}${e.message}`,await r.writeFile(g,D(C,N)),n(),new Error(`${o}`)}n()}try{return await r.writeFile(g,D(C,N)),!0}catch(e){throw new Error(`download article Error ${w}: ${e.message}`)}}function D(e,t){const{articleTitle:r,articleUrl:o,ignoreToc:s}=t;let n=e;n=n.replace(/<br(\s?)\/>/gm,"\n"),n=n.replace(/<a.*?>(\s*?)<\/a>/gm,"");const i=r?`# ${r}\n\n`:"";let a=s?"":h(n).content;a&&(a=`${a}\n\n---\n\n`);return n=`${i}${a}${n}${o?`\n\n> 原文: <${o}>`:""}`,n}exports.logger=$,exports.main=async function(s,n){const{bookId:i,tocList:c,bookName:l,bookDesc:u,bookSlug:h,host:p,imageServiceDomains:d}=await((e,t)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return a.get(e,L(t)).then((({data:e="",status:t})=>200===t?e:"")).then((e=>{const t=r.exec(e)??"";if(!t[1])return{};const o=JSON.parse(decodeURIComponent(t[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||m,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((()=>({})))})(s,{token:n.token,key:n.key});if(!i)throw new Error("No found book id");if(!c||0===c.length)throw new Error("No found toc list");const f=o.resolve(n.distDir,l?S(l):String(i));await r.mkdir(f,{recursive:!0});const g=c.length,w=new k(f,g);if(await w.init(),w.curr===g)return w.bar&&w.bar.stop(),void $.info(`√ 已完成: ${f}`);const y=new Map;w.isDownloadInterrupted&&w.progressInfo.forEach((e=>{y.set(e.toc.uuid,e)}));const I=s.replace(new RegExp(`(.*?/${h}).*`),"$1");await async function(s){const{articleUrlPrefix:n,total:i,uuidMap:a,tocList:c,bookPath:l,bookId:u,progressBar:h,host:p,options:d,imageServiceDomains:f=[]}=s;let g=0,m=0,w=0;const k=[],y=[];for(let o=0;o<i;o++){const s=c[o];if("string"!=typeof s.type)continue;if(a.get(s.uuid))continue;const n=s.type.toLocaleLowerCase();if(n===e.TITLE||""!==s.child_uuid||n===e.LINK){let o=s;const i=[],c=[];for(;o;)i.unshift(S(o.title)),c.unshift(o.uuid),o=a.get(o.parent_uuid)?a.get(o.parent_uuid).toc:void 0;const u={path:i.map(S).join("/"),pathTitleList:i,pathIdList:c,toc:s};n===e.LINK?(w+=1,y.push(u)):await r.mkdir(`${l}/${i.map(S).join("/")}`,{recursive:!0}),a.set(s.uuid,u),n===t.DOC?await b(s):await h.updateProgress(u,n!==e.LINK)}else s.url&&await b(s)}async function b(e){m+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const s=e.type.toLocaleLowerCase();a.get(e.parent_uuid)&&(r=a.get(e.parent_uuid));const i=S(e.title),c=[...r.pathTitleList,i],w=[...r.pathIdList,e.uuid];let $=[...r.pathTitleList,`${i}.md`].map(S).join("/"),y=r.pathTitleList.map(S).join("/");s===t.DOC&&e.child_uuid&&($=[...r.pathTitleList,i,"index.md"].map(S).join("/"),y=c.map(S).join("/"));const b={path:$,savePath:y,pathTitleList:c,pathIdList:w,toc:e};let I=!0;const L=`${n}/${e.url}`;try{const t={bookId:u,itemUrl:e.url,savePath:o.resolve(l,b.savePath),saveFilePath:o.resolve(l,b.path),uuid:e.uuid,articleUrl:L,articleTitle:e.title,ignoreImg:d.ignoreImg,host:p,imageServiceDomains:f};await P({articleInfo:t,progressBar:h,options:d})}catch(e){I=!1,g+=1,k.push({articleUrl:L,errItem:b,errMsg:e.message,err:e})}a.set(e.uuid,b),await h.updateProgress(b,I)}if(w>0){$.warn("该知识库存在以下外链文章");for(const e of y)$.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(g>0){$.error(`本次执行总数${m}篇,✕ 失败${g}篇`);for(const e of k)$.error(`《${e.errItem.path}》: ${e.articleUrl}`),$.error(`———— ✕ ${e.errMsg}`);$.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:I,total:g,uuidMap:y,tocList:c,bookPath:f,bookId:i,progressBar:w,host:p,options:n,imageServiceDomains:d});const v=new b({bookPath:f,bookName:l,bookDesc:u,uuidMap:y});await v.genFile(),$.info(`√ 生成目录 ${o.resolve(f,"SUMMARY.md")}`),w.curr===g&&$.info(`√ 已完成: ${f}`)};
|
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";require("node:fs/promises"),require("node:path");var e=require("./index-
|
|
1
|
+
"use strict";require("node:fs/promises"),require("node:path");var e=require("./index-731e1a03.js");require("rand-user-agent"),require("log4js"),require("cli-progress"),require("axios"),require("node:process"),require("ora"),require("pull-md-img"),require("markdown-toc"),require("pako"),require("node:crypto"),exports.main=e.main;
|
package/dist/es/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as o}from"node:fs";import{cac as e}from"cac";import r from"semver";import{m as t,l as i}from"./index-
|
|
1
|
+
import{readFileSync as o}from"node:fs";import{cac as e}from"cac";import r from"semver";import{m as t,l as i}from"./index-094ab228.js";import"rand-user-agent";import"node:fs/promises";import"cli-progress";import"node:path";import"log4js";import"axios";import"node:process";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";const s=e("yuque-dl"),{version:n,engines:p}=JSON.parse(o(new URL("../../package.json",import.meta.url)).toString());!function(){const o=p.node;r.satisfies(process.version,o)||(i.error(`✕ nodejs 版本需 ${o}, 当前版本为 ${process.version}`),process.exit(1))}(),s.command("<url>","语雀知识库url").option("-d, --dist-dir <dir>","下载的目录 eg: -d download",{default:"download"}).option("-i, --ignore-img","忽略图片不下载",{default:!1}).option("-k, --key <key>",'语雀的cookie key, 默认是 "_yuque_session", 在某些企业版本中 key 不一样').option("-t, --token <token>","语雀的cookie key 对应的值").option("--ignore-toc","默认输出toc目录,添加此参数则不输出toc目录",{default:!1}).action((async(o,e)=>{try{await t(o,e),process.exit(0)}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}})),s.help(),s.version(n);try{s.parse()}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t,{writeFile as e,mkdir as r}from"node:fs/promises";import o from"node:path";import n from"rand-user-agent";import s from"log4js";import i from"cli-progress";import a from"axios";import{env as c,stdout as l}from"node:process";import u from"ora";import p from"pull-md-img";import h from"markdown-toc";import d from"pako";import f from"node:crypto";var m,g;!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(m||(m={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(g||(g={}));const w=new Map([[g.BOARD,"画板类型"],[g.TABLE,"数据表类型"],[g.SHEET,"表格类型"],[g.DOC,"文档类型"]]),$="_yuque_session",k="https://www.yuque.com",y="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",b=(s.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),s.getLogger("yuque-dl"));class I{constructor(t,e){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=t,this.progressFilePath=`${t}/progress.json`,this.total=e}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,b.info("根据上次数据继续断点下载")),this.bar=new i.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},i.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const r=await t.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await t.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,r){this.curr!==this.total&&(this.curr=this.curr+1,r&&(this.progressInfo.push(e),await t.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log(""))))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(t){if(!(t<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let e=0;e<t;e++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}function L({browser:t="chrome",os:e="mac os",device:r="desktop"}){r=r.toLowerCase(),t=t.toLowerCase(),e=e.toLowerCase();let o=n(r,t,e);if("chrome"===t)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=n(r,t,e);if("safari"===t)for(;o.includes("Applebot");)o=n(r,t,e);return o}class v{constructor(t){this.summaryInfo=t}async genFile(){const{bookName:e,bookDesc:r,bookPath:o,uuidMap:n}=this.summaryInfo;let s=`# ${e}\n\n`;r&&(s+=`> ${r}\n\n`);let i=s;const a=[];n.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(a,r),n={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:"link"},s=e.type.toLocaleLowerCase();s===m.TITLE||""!==e.child_uuid?(n.type="title","boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),n.level=o.level+1,o.children.push(n)):(n.level=1,a.push(n)),s===m.DOC&&(n.link=t.path)):(n.type="link",n.link=s===m.LINK?t.toc.url:t.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),n.level=o.level+1,o.children.push(n)):(n.level=1,a.push(n)))}));i+=this.genSummaryContent(a,"");try{await t.writeFile(`${o}/SUMMARY.md`,i)}catch(t){b.error("Generate Summary Error")}return i}genSummaryContent(t,e){for(const r of t){if(r.type===m.TITLE)if(r.link){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`\n${"".padStart(r.level+1,"#")} [${r.text}](${t})\n\n`}else e+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if(r.type===m.LINK){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`- [${r.text}](${t})\n`}Array.isArray(r.children)&&(e+=this.genSummaryContent(r.children,""))}return e}findIdItem(t,e){if(t.id===e)return t;if(t.children){const r=this.findTree(t.children,e);if(r)return r}return!1}findTree(t,e){if(!e)return!1;for(const r of t){const t=this.findIdItem(r,e);if(t)return t}return!1}}function S(t){const{key:e=$,token:r}=t,o={"user-agent":L({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function T(t){return{headers:S(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...S(t)}}}}const E=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:n,key:s,host:i=k}=t;let c=`${i}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};e&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,a.get(c,T({token:n,key:s})).then((({data:t,status:e})=>({apiUrl:c,httpStatus:e,response:t})))};function P(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const D=t=>{if(!t)return"";const e=d.inflate(t,{to:"string"}),r=JSON.parse(e);let o="";return r.forEach((t=>{const e=`## ${t.name}\n`,r=function(t){let e=Object.keys(t);e=e.filter((e=>Object.keys(t[e]).some((r=>t?.[e]?.[r]?.v))));let r=[];e.forEach((e=>{const o=t[e];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...e.map((t=>Number(t)))),n=Math.max(...r.map((t=>Number(t))));if(o<0||n<0)return"";let s="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(n+1).fill(" ").map(((t,e)=>{const r=e%i.length;return i[r]})).join(" | ");a=`| |${a}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${a}\n${c}\n`;for(let e=0;e<o+1;e++){const r=[];for(let o=0;o<n+1;o++){const n=t?.[e]?.[o]?.v||null;n&&"string"==typeof n?r.push(n):n&&"object"==typeof n?"image"===n?.class&&n?.src?r.push(``):"checkbox"===n?.class?r.push(n?.value?"[x] ":"[ ] "):"link"===n?.class?r.push(`[${n?.text}](${n?.url})`):"select"===n?.class&&r.push(n?.value?.join(",")):r.push(null)}s=`${s}${`| ${e+1} | ${r.join(" | ")}|`}\n`}return s}(t.data);o=`${o}\n${e}\n${r}`})),o};function U(t,e=[]){return function(t,e){try{const{host:r,pathname:o}=new URL(t);return!e.includes(r)&&Boolean(o)}catch(t){return!1}}(t,e)?`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(t)}&sign=${function(t){const e=f.createHash("sha256");return e.update(`${y}${t}`),e.digest("hex")}(t)}`:t}async function C(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:s,key:i}=n,{bookId:a,itemUrl:h,savePath:d,saveFilePath:f,uuid:m,articleUrl:$,articleTitle:k,ignoreImg:y,host:b,imageServiceDomains:I}=r,L={articleUrl:h,bookId:a,token:s,host:b,key:i},{httpStatus:v,apiUrl:S,response:T}=await E(L),P=T?.data?.type?.toLocaleLowerCase();let C="";if(P===g.SHEET){const{response:t}=await E(L,!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;C=o?D(o):""}catch(t){const e=w.get(P);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([g.BOARD,g.TABLE].includes(P)){const t=w.get(P);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof T?.data?.sourcecode)throw new Error(`download article Error: ${S}, http status ${v}`);C=T.data.sourcecode,C=function(t){const e=/!\[(.*?)\]\((http.*?latex.*?)\)/gm,r=t.match(e);let o=t;const n=t;try{r?.forEach((t=>{e.lastIndex=0;const r=e.exec(t)?.[2]??"",{pathname:n,search:s}=new URL(r);if(!n.endsWith(".svg")&&s){const e=decodeURIComponent(s);o=o.replace(t,e.slice(1))}}))}catch(t){return n}return o}(C)}const x=function(t){if(!t)return[];const e=/!\[(.*?)\]\((.*?)\)/gm;let r=Array.from(t.match(e)||[]);return r=r.map((t=>(t=t.replace(e,"$2"),/^http.*/g.test(t)?t:""))).filter((t=>Boolean(t))),r}(C);if(x.length&&!y){const t=await E(L,!1);C=function(t,e,r){if(!r)return e;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,i=!0;for(;i||Boolean(s);)if(i=!1,s=o.exec(r),s?.[1])try{const t=decodeURIComponent(s[1]),e=JSON.parse(t);n.push(e?.src||"")}catch{n.push("")}const a=new Map;return t.forEach((t=>{const{origin:r,pathname:o}=new URL(t),s=`${r}${o}`,i=n.find(((t,e)=>{const r=new RegExp(`${s}.*?`).test(t);return r&&n.splice(e,1),r}));if(i){const r=new RegExp(t,"g"),o=a.get(t)||0;let n=0;e=e.replace(r,(t=>{let e=t;return n===o&&(e=i),n+=1,e})),a.set(t,o+1)}})),e}(x,C,t.response?.data?.content??"")}const O={ignoreToc:n.ignoreToc,articleTitle:k,articleUrl:$};if(x.length&&!y){let t;o.pause(),console.log(""),"test"!==c.NODE_ENV&&(t=u({text:`下载 "${k}" 的图片中...`,stream:l}),t.start());const{data:r,errorInfo:n}=await p.run(C,{dist:d,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:$||"",transform:t=>U(t,I)});C=r;const s=()=>{t&&t.stop(),o.continue()};if(n.length>0){const t=`图片下载失败(失败的以远程链接保存): ${n[0].url}`;throw await e(f,N(C,O)),s(),new Error(`${t}`)}s()}try{return await e(f,N(C,O)),!0}catch(t){throw new Error(`download article Error ${$}: ${t.message}`)}}function N(t,e){const{articleTitle:r,articleUrl:o,ignoreToc:n}=e;let s=t;s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const i=r?`# ${r}\n\n`:"";let a=n?"":h(s).content;a&&(a=`${a}\n\n---\n\n`);return s=`${i}${a}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}async function x(t,e){const{bookId:n,tocList:s,bookName:i,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:p}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return a.get(t,T(e)).then((({data:t="",status:e})=>200===e?t:"")).then((t=>{const e=r.exec(t)??"";if(!e[1])return{};const o=JSON.parse(decodeURIComponent(e[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||k,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((()=>({})))})(t,{token:e.token,key:e.key});if(!n)throw new Error("No found book id");if(!s||0===s.length)throw new Error("No found toc list");const h=o.resolve(e.distDir,i?P(i):String(n));await r(h,{recursive:!0});const d=s.length,f=new I(h,d);if(await f.init(),f.curr===d)return f.bar&&f.bar.stop(),void b.info(`√ 已完成: ${h}`);const w=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((t=>{w.set(t.toc.uuid,t)}));const $=t.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:n,uuidMap:s,tocList:i,bookPath:a,bookId:c,progressBar:l,host:u,options:p,imageServiceDomains:h=[]}=t;let d=0,f=0,w=0;const $=[],k=[];for(let t=0;t<n;t++){const e=i[t];if("string"!=typeof e.type)continue;if(s.get(e.uuid))continue;const o=e.type.toLocaleLowerCase();if(o===m.TITLE||""!==e.child_uuid||o===m.LINK){let t=e;const n=[],i=[];for(;t;)n.unshift(P(t.title)),i.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const c={path:n.map(P).join("/"),pathTitleList:n,pathIdList:i,toc:e};o===m.LINK?(w+=1,k.push(c)):await r(`${a}/${n.map(P).join("/")}`,{recursive:!0}),s.set(e.uuid,c),o===g.DOC?await y(e):await l.updateProgress(c,o!==m.LINK)}else e.url&&await y(e)}async function y(t){f+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const n=t.type.toLocaleLowerCase();s.get(t.parent_uuid)&&(r=s.get(t.parent_uuid));const i=P(t.title),m=[...r.pathTitleList,i],w=[...r.pathIdList,t.uuid];let k=[...r.pathTitleList,`${i}.md`].map(P).join("/"),y=r.pathTitleList.map(P).join("/");n===g.DOC&&t.child_uuid&&(k=[...r.pathTitleList,i,"index.md"].map(P).join("/"),y=m.map(P).join("/"));const b={path:k,savePath:y,pathTitleList:m,pathIdList:w,toc:t};let I=!0;const L=`${e}/${t.url}`;try{const e={bookId:c,itemUrl:t.url,savePath:o.resolve(a,b.savePath),saveFilePath:o.resolve(a,b.path),uuid:t.uuid,articleUrl:L,articleTitle:t.title,ignoreImg:p.ignoreImg,host:u,imageServiceDomains:h};await C({articleInfo:e,progressBar:l,options:p})}catch(t){I=!1,d+=1,$.push({articleUrl:L,errItem:b,errMsg:t.message,err:t})}s.set(t.uuid,b),await l.updateProgress(b,I)}if(w>0){b.warn("该知识库存在以下外链文章");for(const t of k)b.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(d>0){b.error(`本次执行总数${f}篇,✕ 失败${d}篇`);for(const t of $)b.error(`《${t.errItem.path}》: ${t.articleUrl}`),b.error(`———— ✕ ${t.errMsg}`);b.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:$,total:d,uuidMap:w,tocList:s,bookPath:h,bookId:n,progressBar:f,host:u,options:e,imageServiceDomains:p});const y=new v({bookPath:h,bookName:i,bookDesc:c,uuidMap:w});await y.genFile(),b.info(`√ 生成目录 ${o.resolve(h,"SUMMARY.md")}`),f.curr===d&&b.info(`√ 已完成: ${h}`)}export{b as l,x as m};
|
|
1
|
+
import t,{writeFile as e,mkdir as r}from"node:fs/promises";import o from"node:path";import n from"rand-user-agent";import s from"log4js";import i from"cli-progress";import a from"axios";import{env as c,stdout as l}from"node:process";import u from"ora";import p from"pull-md-img";import h from"markdown-toc";import d from"pako";import f from"node:crypto";var m,g;!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(m||(m={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(g||(g={}));const w=new Map([[g.BOARD,"画板类型"],[g.TABLE,"数据表类型"],[g.SHEET,"表格类型"],[g.DOC,"文档类型"]]),$="_yuque_session",k="https://www.yuque.com",y="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",b=(s.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),s.getLogger("yuque-dl"));class I{constructor(t,e){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=t,this.progressFilePath=`${t}/progress.json`,this.total=e}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,b.info("根据上次数据继续断点下载")),this.bar=new i.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},i.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const r=await t.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await t.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,r){this.curr!==this.total&&(this.curr=this.curr+1,r&&(this.progressInfo.push(e),await t.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log(""))))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(t){if(!(t<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let e=0;e<t;e++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}function L({browser:t="chrome",os:e="mac os",device:r="desktop"}){r=r.toLowerCase(),t=t.toLowerCase(),e=e.toLowerCase();let o=n(r,t,e);if("chrome"===t)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=n(r,t,e);if("safari"===t)for(;o.includes("Applebot");)o=n(r,t,e);return o}class v{constructor(t){this.summaryInfo=t}async genFile(){const{bookName:e,bookDesc:r,bookPath:o,uuidMap:n}=this.summaryInfo;let s=`# ${e}\n\n`;r&&(s+=`> ${r}\n\n`);let i=s;const a=[];n.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(a,r),n={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:"link"},s=e.type.toLocaleLowerCase();s===m.TITLE||""!==e.child_uuid?(n.type="title","boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),n.level=o.level+1,o.children.push(n)):(n.level=1,a.push(n)),s===m.DOC&&(n.link=t.path)):(n.type="link",n.link=s===m.LINK?t.toc.url:t.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),n.level=o.level+1,o.children.push(n)):(n.level=1,a.push(n)))}));i+=this.genSummaryContent(a,"");try{await t.writeFile(`${o}/SUMMARY.md`,i)}catch(t){b.error("Generate Summary Error")}return i}genSummaryContent(t,e){for(const r of t){if(r.type===m.TITLE)if(r.link){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`\n${"".padStart(r.level+1,"#")} [${r.text}](${t})\n\n`}else e+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if(r.type===m.LINK){const t=r.link?r.link.replace(/\s/g,"%20"):r.link;e+=`- [${r.text}](${t})\n`}Array.isArray(r.children)&&(e+=this.genSummaryContent(r.children,""))}return e}findIdItem(t,e){if(t.id===e)return t;if(t.children){const r=this.findTree(t.children,e);if(r)return r}return!1}findTree(t,e){if(!e)return!1;for(const r of t){const t=this.findIdItem(r,e);if(t)return t}return!1}}function S(t){const{key:e=$,token:r}=t,o={"user-agent":L({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function T(t){return{headers:S(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...S(t)}}}}const E=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:n,key:s,host:i=k}=t;let c=`${i}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};e&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,a.get(c,T({token:n,key:s})).then((({data:t,status:e})=>({apiUrl:c,httpStatus:e,response:t})))};function P(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const D=t=>{if(!t)return"";const e=d.inflate(t,{to:"string"}),r=JSON.parse(e);let o="";return r.forEach((t=>{const e=`## ${t.name}\n`,r=function(t){let e=Object.keys(t);e=e.filter((e=>Object.keys(t[e]).some((r=>t?.[e]?.[r]?.v))));let r=[];e.forEach((e=>{const o=t[e];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...e.map((t=>Number(t)))),n=Math.max(...r.map((t=>Number(t))));if(o<0||n<0)return"";let s="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(n+1).fill(" ").map(((t,e)=>{const r=e%i.length;return i[r]})).join(" | ");a=`| |${a}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${a}\n${c}\n`;for(let e=0;e<o+1;e++){const r=[];for(let o=0;o<n+1;o++){const n=t?.[e]?.[o]?.v||null;n&&"string"==typeof n?r.push(n):n&&"object"==typeof n?"image"===n?.class&&n?.src?r.push(``):"checkbox"===n?.class?r.push(n?.value?"[x] ":"[ ] "):"link"===n?.class?r.push(`[${n?.text}](${n?.url})`):"select"===n?.class&&r.push(n?.value?.join(",")):r.push(null)}s=`${s}${`| ${e+1} | ${r.join(" | ")}|`}\n`}return s}(t.data);o=`${o}\n${e}\n${r}`})),o};function U(t,e=[]){return function(t,e){try{const{host:r,pathname:o}=new URL(t);return!e.includes(r)&&Boolean(o)}catch(t){return!1}}(t,e)?`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(t)}&sign=${function(t){const e=f.createHash("sha256");return e.update(`${y}${t}`),e.digest("hex")}(t)}`:t}async function C(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:s,key:i}=n,{bookId:a,itemUrl:h,savePath:d,saveFilePath:f,uuid:m,articleUrl:$,articleTitle:k,ignoreImg:y,host:b,imageServiceDomains:I}=r,L={articleUrl:h,bookId:a,token:s,host:b,key:i},{httpStatus:v,apiUrl:S,response:T}=await E(L),P=T?.data?.type?.toLocaleLowerCase();let C="";if(P===g.SHEET){const{response:t}=await E(L,!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;C=o?D(o):""}catch(t){const e=w.get(P);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([g.BOARD,g.TABLE].includes(P)){const t=w.get(P);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof T?.data?.sourcecode)throw new Error(`download article Error: ${S}, http status ${v}`);C=T.data.sourcecode,C=function(t){const e=/!\[(.*?)\]\((http.*?latex.*?)\)/gm,r=t.match(e);let o=t;const n=t;try{r?.forEach((t=>{e.lastIndex=0;const r=e.exec(t)?.[2]??"",{pathname:n,search:s}=new URL(r);if(!n.endsWith(".svg")&&s){const e=decodeURIComponent(s);o=o.replace(t,e.slice(1))}}))}catch(t){return n}return o}(C)}const x=function(t){if(!t)return[];const e=/!\[(.*?)\]\((.*?)\)/gm;let r=Array.from(t.match(e)||[]);return r=r.map((t=>(t=t.replace(e,"$2"),/^http.*/g.test(t)?t:""))).filter((t=>Boolean(t))),r}(C);if(x.length&&!y){const t=await E(L,!1);C=function(t,e,r){if(!r)return e;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,i=!0;for(;i||Boolean(s);)if(i=!1,s=o.exec(r),s?.[1])try{const t=decodeURIComponent(s[1]),e=JSON.parse(t);n.push(e?.src||"")}catch{n.push("")}const a=new Map;return t.forEach((t=>{const{origin:r,pathname:o}=new URL(t),s=`${r}${o}`,i=n.find(((t,e)=>{const r=new RegExp(`${s}.*?`).test(t);return r&&n.splice(e,1),r}));if(i){const r=new RegExp(t,"g"),o=a.get(t)||0;let n=0;e=e.replace(r,(t=>{let e=t;return n===o&&(e=i),n+=1,e})),a.set(t,o+1)}})),e}(x,C,t.response?.data?.content??"")}const O={ignoreToc:n.ignoreToc,articleTitle:k,articleUrl:$};if(x.length&&!y){let t;o.pause(),console.log(""),"test"!==c.NODE_ENV&&(t=u({text:`下载 "${k}" 的图片中...`,stream:l}),t.start());let r=[],n=C;try{const t=await p.run(C,{dist:d,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:$||"",transform:t=>U(t,I)});r=t.errorInfo,n=t.data}catch(t){r=[t]}C=n;const s=()=>{t&&t.stop(),o.continue()};if(r.length>0){const t=r[0];let o="图片下载失败(失败的以远程链接保存): ";throw o=t.url?`${o}${t.error?.message} ${t.url.slice(0,20)}...`:`${o}${t.message}`,await e(f,N(C,O)),s(),new Error(`${o}`)}s()}try{return await e(f,N(C,O)),!0}catch(t){throw new Error(`download article Error ${$}: ${t.message}`)}}function N(t,e){const{articleTitle:r,articleUrl:o,ignoreToc:n}=e;let s=t;s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const i=r?`# ${r}\n\n`:"";let a=n?"":h(s).content;a&&(a=`${a}\n\n---\n\n`);return s=`${i}${a}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}async function x(t,e){const{bookId:n,tocList:s,bookName:i,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:p}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return a.get(t,T(e)).then((({data:t="",status:e})=>200===e?t:"")).then((t=>{const e=r.exec(t)??"";if(!e[1])return{};const o=JSON.parse(decodeURIComponent(e[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||k,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((()=>({})))})(t,{token:e.token,key:e.key});if(!n)throw new Error("No found book id");if(!s||0===s.length)throw new Error("No found toc list");const h=o.resolve(e.distDir,i?P(i):String(n));await r(h,{recursive:!0});const d=s.length,f=new I(h,d);if(await f.init(),f.curr===d)return f.bar&&f.bar.stop(),void b.info(`√ 已完成: ${h}`);const w=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((t=>{w.set(t.toc.uuid,t)}));const $=t.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:n,uuidMap:s,tocList:i,bookPath:a,bookId:c,progressBar:l,host:u,options:p,imageServiceDomains:h=[]}=t;let d=0,f=0,w=0;const $=[],k=[];for(let t=0;t<n;t++){const e=i[t];if("string"!=typeof e.type)continue;if(s.get(e.uuid))continue;const o=e.type.toLocaleLowerCase();if(o===m.TITLE||""!==e.child_uuid||o===m.LINK){let t=e;const n=[],i=[];for(;t;)n.unshift(P(t.title)),i.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const c={path:n.map(P).join("/"),pathTitleList:n,pathIdList:i,toc:e};o===m.LINK?(w+=1,k.push(c)):await r(`${a}/${n.map(P).join("/")}`,{recursive:!0}),s.set(e.uuid,c),o===g.DOC?await y(e):await l.updateProgress(c,o!==m.LINK)}else e.url&&await y(e)}async function y(t){f+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const n=t.type.toLocaleLowerCase();s.get(t.parent_uuid)&&(r=s.get(t.parent_uuid));const i=P(t.title),m=[...r.pathTitleList,i],w=[...r.pathIdList,t.uuid];let k=[...r.pathTitleList,`${i}.md`].map(P).join("/"),y=r.pathTitleList.map(P).join("/");n===g.DOC&&t.child_uuid&&(k=[...r.pathTitleList,i,"index.md"].map(P).join("/"),y=m.map(P).join("/"));const b={path:k,savePath:y,pathTitleList:m,pathIdList:w,toc:t};let I=!0;const L=`${e}/${t.url}`;try{const e={bookId:c,itemUrl:t.url,savePath:o.resolve(a,b.savePath),saveFilePath:o.resolve(a,b.path),uuid:t.uuid,articleUrl:L,articleTitle:t.title,ignoreImg:p.ignoreImg,host:u,imageServiceDomains:h};await C({articleInfo:e,progressBar:l,options:p})}catch(t){I=!1,d+=1,$.push({articleUrl:L,errItem:b,errMsg:t.message,err:t})}s.set(t.uuid,b),await l.updateProgress(b,I)}if(w>0){b.warn("该知识库存在以下外链文章");for(const t of k)b.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(d>0){b.error(`本次执行总数${f}篇,✕ 失败${d}篇`);for(const t of $)b.error(`《${t.errItem.path}》: ${t.articleUrl}`),b.error(`———— ✕ ${t.errMsg}`);b.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:$,total:d,uuidMap:w,tocList:s,bookPath:h,bookId:n,progressBar:f,host:u,options:e,imageServiceDomains:p});const y=new v({bookPath:h,bookName:i,bookDesc:c,uuidMap:w});await y.genFile(),b.info(`√ 生成目录 ${o.resolve(h,"SUMMARY.md")}`),f.curr===d&&b.info(`√ 已完成: ${h}`)}export{b as l,x as m};
|
package/dist/es/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:fs/promises";import"node:path";export{m as main}from"./index-
|
|
1
|
+
import"node:fs/promises";import"node:path";export{m as main}from"./index-094ab228.js";import"rand-user-agent";import"log4js";import"cli-progress";import"axios";import"node:process";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "yuque-dl",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.51",
|
|
4
4
|
"description": "yuque 知识库下载",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"markdown-toc": "^1.2.0",
|
|
63
63
|
"ora": "^7.0.1",
|
|
64
64
|
"pako": "1.0.11",
|
|
65
|
-
"pull-md-img": "^0.0.
|
|
65
|
+
"pull-md-img": "^0.0.59",
|
|
66
66
|
"rand-user-agent": "1.0.109",
|
|
67
67
|
"semver": "^7.6.0"
|
|
68
68
|
},
|
package/types/types/index.d.ts
CHANGED
|
@@ -62,7 +62,7 @@ export interface IProgressItem {
|
|
|
62
62
|
pathIdList: string[];
|
|
63
63
|
pathTitleList: string[];
|
|
64
64
|
}
|
|
65
|
-
export type IProgress = IProgressItem[];
|
|
65
|
+
export declare type IProgress = IProgressItem[];
|
|
66
66
|
export interface IGenSummaryFile {
|
|
67
67
|
bookPath: string;
|
|
68
68
|
bookName?: string;
|
|
@@ -123,7 +123,7 @@ export interface GetHeaderParams {
|
|
|
123
123
|
/** token value */
|
|
124
124
|
token?: string;
|
|
125
125
|
}
|
|
126
|
-
export type TGetKnowledgeBaseInfo = (url: string, headerParams: GetHeaderParams) => Promise<IKnowledgeBaseInfo>;
|
|
126
|
+
export declare type TGetKnowledgeBaseInfo = (url: string, headerParams: GetHeaderParams) => Promise<IKnowledgeBaseInfo>;
|
|
127
127
|
export interface GetMdDataParams {
|
|
128
128
|
articleUrl: string;
|
|
129
129
|
bookId: number;
|
|
@@ -136,6 +136,6 @@ export interface IGetDocsMdDataRes {
|
|
|
136
136
|
httpStatus: number;
|
|
137
137
|
response?: ArticleResponse.RootObject;
|
|
138
138
|
}
|
|
139
|
-
export type TGetMdData = (params: GetMdDataParams, isMd?: boolean) => Promise<IGetDocsMdDataRes>;
|
|
139
|
+
export declare type TGetMdData = (params: GetMdDataParams, isMd?: boolean) => Promise<IGetDocsMdDataRes>;
|
|
140
140
|
export * from './ArticleResponse';
|
|
141
141
|
export * from './KnowledgeBaseResponse';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";var e,t,r=require("node:fs/promises"),o=require("node:path"),n=require("rand-user-agent"),s=require("log4js"),i=require("cli-progress"),a=require("axios"),c=require("node:process"),l=require("ora"),u=require("pull-md-img"),h=require("markdown-toc"),p=require("pako"),d=require("node:crypto");!function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(e||(e={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(t||(t={}));const f=new Map([[t.BOARD,"画板类型"],[t.TABLE,"数据表类型"],[t.SHEET,"表格类型"],[t.DOC,"文档类型"]]),g="_yuque_session",m="https://www.yuque.com",w="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",$=(s.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),s.getLogger("yuque-dl"));class k{constructor(e,t){this.bookPath="",this.progressFilePath="",this.progressInfo=[],this.curr=0,this.total=0,this.isDownloadInterrupted=!1,this.bar=null,this.completePromise=null,this.bookPath=e,this.progressFilePath=`${e}/progress.json`,this.total=t}async init(){this.progressInfo=await this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,$.info("根据上次数据继续断点下载")),this.bar=new i.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},i.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let e=[];try{const t=await r.readFile(this.progressFilePath,{encoding:"utf8"});e=JSON.parse(t)}catch(t){t&&"ENOENT"===t.code&&await r.writeFile(this.progressFilePath,JSON.stringify(e),{encoding:"utf8"})}return e}async updateProgress(e,t){this.curr!==this.total&&(this.curr=this.curr+1,t&&(this.progressInfo.push(e),await r.writeFile(this.progressFilePath,JSON.stringify(this.progressInfo),{encoding:"utf8"})),this.bar&&(this.bar.update(this.curr),this.curr>=this.total&&(this.bar.stop(),console.log(""))))}pause(){this.bar&&this.bar.stop()}continue(){this.clearLine(2),this.bar?.start(this.total,this.curr)}clearLine(e){if(!(e<=0)&&"function"==typeof process?.stderr?.cursorTo){process.stderr.cursorTo(0);for(let t=0;t<e;t++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}function y({browser:e="chrome",os:t="mac os",device:r="desktop"}){r=r.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let o=n(r,e,t);if("chrome"===e)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=n(r,e,t);if("safari"===e)for(;o.includes("Applebot");)o=n(r,e,t);return o}class b{constructor(e){this.summaryInfo=e}async genFile(){const{bookName:t,bookDesc:o,bookPath:n,uuidMap:s}=this.summaryInfo;let i=`# ${t}\n\n`;o&&(i+=`> ${o}\n\n`);let a=i;const c=[];s.forEach((t=>{const r=t.toc,o=r.parent_uuid,n=this.findTree(c,o),s={text:r.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:r.uuid,level:1,type:"link"},i=r.type.toLocaleLowerCase();i===e.TITLE||""!==r.child_uuid?(s.type="title","boolean"!=typeof n?(Array.isArray(n.children)||(n.children=[]),s.level=n.level+1,n.children.push(s)):(s.level=1,c.push(s)),i===e.DOC&&(s.link=t.path)):(s.type="link",s.link=i===e.LINK?t.toc.url:t.path,"boolean"!=typeof n?(Array.isArray(n.children)||(n.children=[]),s.level=n.level+1,n.children.push(s)):(s.level=1,c.push(s)))}));a+=this.genSummaryContent(c,"");try{await r.writeFile(`${n}/SUMMARY.md`,a)}catch(e){$.error("Generate Summary Error")}return a}genSummaryContent(t,r){for(const o of t){if(o.type===e.TITLE)if(o.link){const e=o.link?o.link.replace(/\s/g,"%20"):o.link;r+=`\n${"".padStart(o.level+1,"#")} [${o.text}](${e})\n\n`}else r+=`\n${"".padStart(o.level+1,"#")} ${o.text}\n\n`;else if(o.type===e.LINK){const e=o.link?o.link.replace(/\s/g,"%20"):o.link;r+=`- [${o.text}](${e})\n`}Array.isArray(o.children)&&(r+=this.genSummaryContent(o.children,""))}return r}findIdItem(e,t){if(e.id===t)return e;if(e.children){const r=this.findTree(e.children,t);if(r)return r}return!1}findTree(e,t){if(!t)return!1;for(const r of e){const e=this.findIdItem(r,t);if(e)return e}return!1}}function I(e){const{key:t=g,token:r}=e,o={"user-agent":y({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${t}=${r};`),o}function L(e){return{headers:I(e),beforeRedirect:t=>{t.headers={...t?.headers||{},...I(e)}}}}const v=(e,t=!0)=>{const{articleUrl:r,bookId:o,token:n,key:s,host:i=m}=e;let c=`${i}/api/docs/${r}`;const l={book_id:String(o),merge_dynamic_data:String(!1)};t&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,a.get(c,L({token:n,key:s})).then((({data:e,status:t})=>({apiUrl:c,httpStatus:t,response:e})))};function S(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const T=e=>{if(!e)return"";const t=p.inflate(e,{to:"string"}),r=JSON.parse(t);let o="";return r.forEach((e=>{const t=`## ${e.name}\n`,r=function(e){let t=Object.keys(e);t=t.filter((t=>Object.keys(e[t]).some((r=>e?.[t]?.[r]?.v))));let r=[];t.forEach((t=>{const o=e[t];o&&(r=r.concat(Object.keys(o)))}));const o=Math.max(...t.map((e=>Number(e)))),n=Math.max(...r.map((e=>Number(e))));if(o<0||n<0)return"";let s="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let a=Array(n+1).fill(" ").map(((e,t)=>{const r=t%i.length;return i[r]})).join(" | ");a=`| |${a}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${a}\n${c}\n`;for(let t=0;t<o+1;t++){const r=[];for(let o=0;o<n+1;o++){const n=e?.[t]?.[o]?.v||null;n&&"string"==typeof n?r.push(n):n&&"object"==typeof n?"image"===n?.class&&n?.src?r.push(``):"checkbox"===n?.class?r.push(n?.value?"[x] ":"[ ] "):"link"===n?.class?r.push(`[${n?.text}](${n?.url})`):"select"===n?.class&&r.push(n?.value?.join(",")):r.push(null)}s=`${s}${`| ${t+1} | ${r.join(" | ")}|`}\n`}return s}(e.data);o=`${o}\n${t}\n${r}`})),o};function E(e,t=[]){return function(e,t){try{const{host:r,pathname:o}=new URL(e);return!t.includes(r)&&Boolean(o)}catch(e){return!1}}(e,t)?`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(e)}&sign=${function(e){const t=d.createHash("sha256");return t.update(`${w}${e}`),t.digest("hex")}(e)}`:e}async function P(e){const{articleInfo:o,progressBar:n,options:s}=e,{token:i,key:a}=s,{bookId:h,itemUrl:p,savePath:d,saveFilePath:g,uuid:m,articleUrl:w,articleTitle:$,ignoreImg:k,host:y,imageServiceDomains:b}=o,I={articleUrl:p,bookId:h,token:i,host:y,key:a},{httpStatus:L,apiUrl:S,response:P}=await v(I),U=P?.data?.type?.toLocaleLowerCase();let C="";if(U===t.SHEET){const{response:e}=await v(I,!1);try{const t=e?.data?.content,r=t?JSON.parse(t):{},o=r?.sheet;C=o?T(o):""}catch(e){const t=f.get(U);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([t.BOARD,t.TABLE].includes(U)){const e=f.get(U);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof P?.data?.sourcecode)throw new Error(`download article Error: ${S}, http status ${L}`);C=P.data.sourcecode,C=function(e){const t=/!\[(.*?)\]\((http.*?latex.*?)\)/gm,r=e.match(t);let o=e;const n=e;try{r?.forEach((e=>{t.lastIndex=0;const r=t.exec(e)?.[2]??"",{pathname:n,search:s}=new URL(r);if(!n.endsWith(".svg")&&s){const t=decodeURIComponent(s);o=o.replace(e,t.slice(1))}}))}catch(e){return n}return o}(C)}const x=function(e){if(!e)return[];const t=/!\[(.*?)\]\((.*?)\)/gm;let r=Array.from(e.match(t)||[]);return r=r.map((e=>(e=e.replace(t,"$2"),/^http.*/g.test(e)?e:""))).filter((e=>Boolean(e))),r}(C);if(x.length&&!k){const e=await v(I,!1);C=function(e,t,r){if(!r)return t;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,i=!0;for(;i||Boolean(s);)if(i=!1,s=o.exec(r),s?.[1])try{const e=decodeURIComponent(s[1]),t=JSON.parse(e);n.push(t?.src||"")}catch{n.push("")}const a=new Map;return e.forEach((e=>{const{origin:r,pathname:o}=new URL(e),s=`${r}${o}`,i=n.find(((e,t)=>{const r=new RegExp(`${s}.*?`).test(e);return r&&n.splice(t,1),r}));if(i){const r=new RegExp(e,"g"),o=a.get(e)||0;let n=0;t=t.replace(r,(e=>{let t=e;return n===o&&(t=i),n+=1,t})),a.set(e,o+1)}})),t}(x,C,e.response?.data?.content??"")}const N={ignoreToc:s.ignoreToc,articleTitle:$,articleUrl:w};if(x.length&&!k){let e;n.pause(),console.log(""),"test"!==c.env.NODE_ENV&&(e=l({text:`下载 "${$}" 的图片中...`,stream:c.stdout}),e.start());const{data:t,errorInfo:o}=await u.run(C,{dist:d,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:w||"",transform:e=>E(e,b)});C=t;const s=()=>{e&&e.stop(),n.continue()};if(o.length>0){const e=`图片下载失败(失败的以远程链接保存): ${o[0].url}`;throw await r.writeFile(g,D(C,N)),s(),new Error(`${e}`)}s()}try{return await r.writeFile(g,D(C,N)),!0}catch(e){throw new Error(`download article Error ${w}: ${e.message}`)}}function D(e,t){const{articleTitle:r,articleUrl:o,ignoreToc:n}=t;let s=e;s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const i=r?`# ${r}\n\n`:"";let a=n?"":h(s).content;a&&(a=`${a}\n\n---\n\n`);return s=`${i}${a}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}exports.logger=$,exports.main=async function(n,s){const{bookId:i,tocList:c,bookName:l,bookDesc:u,bookSlug:h,host:p,imageServiceDomains:d}=await((e,t)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return a.get(e,L(t)).then((({data:e="",status:t})=>200===t?e:"")).then((e=>{const t=r.exec(e)??"";if(!t[1])return{};const o=JSON.parse(decodeURIComponent(t[1]));return o.book?{bookId:o.book.id,bookSlug:o.book.slug,tocList:o.book.toc||[],bookName:o.book.name||"",bookDesc:o.book.description||"",host:o.space?.host||m,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((()=>({})))})(n,{token:s.token,key:s.key});if(!i)throw new Error("No found book id");if(!c||0===c.length)throw new Error("No found toc list");const f=o.resolve(s.distDir,l?S(l):String(i));await r.mkdir(f,{recursive:!0});const g=c.length,w=new k(f,g);if(await w.init(),w.curr===g)return w.bar&&w.bar.stop(),void $.info(`√ 已完成: ${f}`);const y=new Map;w.isDownloadInterrupted&&w.progressInfo.forEach((e=>{y.set(e.toc.uuid,e)}));const I=n.replace(new RegExp(`(.*?/${h}).*`),"$1");await async function(n){const{articleUrlPrefix:s,total:i,uuidMap:a,tocList:c,bookPath:l,bookId:u,progressBar:h,host:p,options:d,imageServiceDomains:f=[]}=n;let g=0,m=0,w=0;const k=[],y=[];for(let o=0;o<i;o++){const n=c[o];if("string"!=typeof n.type)continue;if(a.get(n.uuid))continue;const s=n.type.toLocaleLowerCase();if(s===e.TITLE||""!==n.child_uuid||s===e.LINK){let o=n;const i=[],c=[];for(;o;)i.unshift(S(o.title)),c.unshift(o.uuid),o=a.get(o.parent_uuid)?a.get(o.parent_uuid).toc:void 0;const u={path:i.map(S).join("/"),pathTitleList:i,pathIdList:c,toc:n};s===e.LINK?(w+=1,y.push(u)):await r.mkdir(`${l}/${i.map(S).join("/")}`,{recursive:!0}),a.set(n.uuid,u),s===t.DOC?await b(n):await h.updateProgress(u,s!==e.LINK)}else n.url&&await b(n)}async function b(e){m+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const n=e.type.toLocaleLowerCase();a.get(e.parent_uuid)&&(r=a.get(e.parent_uuid));const i=S(e.title),c=[...r.pathTitleList,i],w=[...r.pathIdList,e.uuid];let $=[...r.pathTitleList,`${i}.md`].map(S).join("/"),y=r.pathTitleList.map(S).join("/");n===t.DOC&&e.child_uuid&&($=[...r.pathTitleList,i,"index.md"].map(S).join("/"),y=c.map(S).join("/"));const b={path:$,savePath:y,pathTitleList:c,pathIdList:w,toc:e};let I=!0;const L=`${s}/${e.url}`;try{const t={bookId:u,itemUrl:e.url,savePath:o.resolve(l,b.savePath),saveFilePath:o.resolve(l,b.path),uuid:e.uuid,articleUrl:L,articleTitle:e.title,ignoreImg:d.ignoreImg,host:p,imageServiceDomains:f};await P({articleInfo:t,progressBar:h,options:d})}catch(e){I=!1,g+=1,k.push({articleUrl:L,errItem:b,errMsg:e.message,err:e})}a.set(e.uuid,b),await h.updateProgress(b,I)}if(w>0){$.warn("该知识库存在以下外链文章");for(const e of y)$.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(g>0){$.error(`本次执行总数${m}篇,✕ 失败${g}篇`);for(const e of k)$.error(`《${e.errItem.path}》: ${e.articleUrl}`),$.error(`———— ✕ ${e.errMsg}`);$.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:I,total:g,uuidMap:y,tocList:c,bookPath:f,bookId:i,progressBar:w,host:p,options:s,imageServiceDomains:d});const v=new b({bookPath:f,bookName:l,bookDesc:u,uuidMap:y});await v.genFile(),$.info(`√ 生成目录 ${o.resolve(f,"SUMMARY.md")}`),w.curr===g&&$.info(`√ 已完成: ${f}`)};
|