yuque-dl 1.0.61 → 1.0.63
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/README.md +1 -1
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/{index-RehN9FDK.js → index-D4Xc6rpR.js} +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/es/cli.js +1 -1
- package/dist/es/index-BYWftZWJ.js +1 -0
- package/dist/es/index.js +1 -1
- package/package.json +1 -1
- package/types/utils/index.d.ts +2 -1
- package/dist/es/index-V56QfIJz.js +0 -1
package/README.md
CHANGED
|
@@ -135,7 +135,7 @@ yuque-dl "https://www.yuque.com/yuque/thyzgp" -t="-a123"
|
|
|
135
135
|
|
|
136
136
|
完全公开的知识库未登录的情况下查看附件:
|
|
137
137
|
|
|
138
|
-

|
|
139
139
|
|
|
140
140
|
## Tips
|
|
141
141
|
|
package/dist/cjs/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:fs"),n=require("cac"),r=require("semver"),t=require("./index-
|
|
1
|
+
"use strict";var e=require("node:fs"),n=require("cac"),r=require("semver"),t=require("./index-D4Xc6rpR.js");require("rand-user-agent");var i=require("node:fs/promises");require("cli-progress");var o=require("vitepress"),s=require("node:path");require("log4js"),require("axios"),require("node:process"),require("ora"),require("pull-md-img"),require("markdown-toc"),require("pako"),require("node:crypto"),require("node:stream"),require("node:util");var a="undefined"!=typeof document?document.currentScript:null;let c;async function d(e){const n=s.resolve(e);if(!await u(n))throw new Error("server root not found");await async function(e){const n=e.split(s.sep).filter(Boolean).at(-1)||"yuque-dl",r=s.join(e,"/.vitepress");await i.mkdir(r,{recursive:!0});const t=s.join(r,"config.ts"),o=await async function(e){const n=[],r=[".vitepress","img","index.md","progress.json","attachments"];let t=await i.readdir(e);t=t.filter((e=>!r.includes(e)));for(const r of t){const t=s.join(e,r);if((await i.stat(t)).isDirectory()){const i=await u(s.join(t,"index.md")),o={text:r,collapsed:!0,items:await l(e,r)};i&&(o.link=`/${r}/`),n.push(o)}else n.push({text:r.slice(0,r.lastIndexOf(".")),link:`/${r}`})}return n}(e),a=`\n export default {\n title: "${n}",\n themeConfig: {\n search: {\n provider: 'local'\n },\n sidebar: ${JSON.stringify(o)}\n },\n vite: {\n optimizeDeps: {\n include: []\n }\n },\n markdown: {\n html: false\n }\n }\n `;await i.writeFile(t,a)}(n);const r=async()=>{const n=await o.createServer(e,{},(async()=>(c||(c=(async()=>{await n.close(),await r()})().finally((()=>{c=void 0}))),c)));await n.listen(),n.printUrls()};await r().catch((e=>{console.error(e),process.exit(1)}))}async function u(e){try{return await i.access(e),!0}catch(e){if("ENOENT"===e.code)return!1;throw e}}async function l(e,...n){const r=await i.readdir(s.join(e,...n)),t=[];for(const o of r){const r=s.join(e,...n,o);if((await i.stat(r)).isDirectory()){const i=await l(s.join(e),...n,o);if(i.length>0){const e={text:o,items:i,collapsed:false};await u(s.join(r,"index.md"))&&(e.link="/"+[...n,o].map(decodeURIComponent).join("/")+"/"),t.push(e)}}else{if("index.md"===o||/^-.*\.(md|MD)$/.test(o)||!o.endsWith(".md"))continue;const e=o.replace(/\.md$/,""),r={text:e,link:"/"+[...n.map(decodeURIComponent),`${encodeURI(e)}.html`].join("/")};t.push(r)}}return t}const p=n.cac("yuque-dl"),{version:m,engines:f}=JSON.parse(e.readFileSync(new URL("../../package.json","undefined"==typeof document?require("url").pathToFileURL(__filename).href:a&&a.src||new URL("cli.js",document.baseURI).href)).toString());!function(){const e=f.node;r.satisfies(process.version,e)||(t.logger.error(`✕ nodejs 版本需 ${e}, 当前版本为 ${process.version}`),process.exit(1))}(),p.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("--toc","是否输出文档toc目录",{default:!1}).action((async(e,n)=>{try{await t.main(e,n),process.exit(0)}catch(e){t.logger.error(e.message||"unknown exception"),process.exit(1)}})),p.command("server <serverPath>","启动web服务").action((async e=>{try{await d(e)}catch(e){t.logger.error(e.message||"unknown exception"),process.exit(1)}})),p.help(),p.version(m);try{p.parse()}catch(e){t.logger.error(e.message||"unknown exception"),process.exit(1)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:fs/promises"),t=require("node:path"),r=require("rand-user-agent"),o=require("log4js"),n=require("cli-progress"),s=require("axios"),a=require("node:process"),i=require("ora"),c=require("pull-md-img"),l=require("markdown-toc"),u=require("pako"),h=require("node:crypto"),p=require("node:stream"),d=require("node:util"),f=require("node:fs");function m(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var g,w,$=m(p);!function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(g||(g={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(w||(w={}));const y=new Map([[w.BOARD,"画板类型"],[w.TABLE,"数据表类型"],[w.SHEET,"表格类型"],[w.DOC,"文档类型"]]),k="_yuque_session",b="https://www.yuque.com",v="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",I=(o.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),o.getLogger("yuque-dl"));class L{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,I.info("根据上次数据继续断点下载")),this.bar=new n.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},n.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let t=[];try{const r=await e.readFile(this.progressFilePath,{encoding:"utf8"});t=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await e.writeFile(this.progressFilePath,JSON.stringify(t),{encoding:"utf8"})}return t}async updateProgress(t,r){this.curr!==this.total&&(this.curr=this.curr+1,r&&(this.progressInfo.push(t),await e.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 E({browser:e="chrome",os:t="mac os",device:o="desktop"}){o=o.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let n=r(o,e,t);if("chrome"===e)for(;n.includes("Chrome-Lighthouse")||n.includes("Gener8")||n.includes("HeadlessChrome")||n.includes("SMTBot");)n=r(o,e,t);if("safari"===e)for(;n.includes("Applebot");)n=r(o,e,t);return n}class S{constructor(e){this.summaryInfo=e}async genFile(){const{bookName:t,bookDesc:r,bookPath:o,uuidMap:n}=this.summaryInfo;let s=`# ${t}\n\n`;r&&(s+=`> ${r}\n\n`);let a=s;const i=[];n.forEach((e=>{const t=e.toc,r=t.parent_uuid,o=this.findTree(i,r),n={text:t.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:t.uuid,level:1,type:"link"},s=t.type.toLocaleLowerCase();s===g.TITLE||""!==t.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,i.push(n)),s===g.DOC&&(n.link=e.path)):(n.type="link",n.link=s===g.LINK?e.toc.url:e.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),n.level=o.level+1,o.children.push(n)):(n.level=1,i.push(n)))}));a+=this.genSummaryContent(i,"");try{await e.writeFile(`${o}/index.md`,a)}catch(e){I.error("Generate Summary Error")}return a}genSummaryContent(e,t){for(const r of e){if(r.type===g.TITLE)if(r.link){const e=r.link?r.link.replace(/\s/g,"%20"):r.link;t+=`\n${"".padStart(r.level+1,"#")} [${r.text}](${e})\n\n`}else t+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if(r.type===g.LINK){const e=r.link?r.link.replace(/\s/g,"%20"):r.link;t+=`- [${r.text}](${e})\n`}Array.isArray(r.children)&&(t+=this.genSummaryContent(r.children,""))}return t}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 P(e){const{key:t=k,token:r}=e,o={"user-agent":E({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${t}=${r};`),o}function T(e){return{headers:P(e),beforeRedirect:t=>{t.headers={...t?.headers||{},...P(e)}}}}const D=(e,t=!0)=>{const{articleUrl:r,bookId:o,token:n,key:a,host:i=b}=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}`,s.get(c,T({token:n,key:a})).then((({data:e,status:t})=>({apiUrl:c,httpStatus:t,response:e})))};function N(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const U=e=>{if(!e)return"";const t=u.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 a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let i=Array(n+1).fill(" ").map(((e,t)=>{const r=t%a.length;return a[r]})).join(" | ");i=`| |${i}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${i}\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 x(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=h.createHash("sha256");return t.update(`${v}${e}`),t.digest("hex")}(e)}`:e}const O=/\[(.*?)\]\((.*?)\)/g,C=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;async function j(e){const{mdData:r,savePath:o,attachmentsDir:n,articleTitle:c,token:l,key:u}=e,h=(r.match(O)||[]).filter((e=>C.test(e)));if(0===h.length)return{mdData:r};const p=i({text:`下载 "${c}" 的附件中...`,stream:a.stdout});"test"!==a.env.NODE_ENV&&p.start();const d=t.resolve(o,n),m=h.map((e=>function(e,r){const[,o,n]=C.exec(e)||[];if(!n)return!1;const s=o||n.split("/").at(-1);if(!s)return!1;const a=t.join(r,s);return{fileName:s,url:n,rawMd:e,currentFilePath:a}}(e,d))).filter((e=>!1!==e));f.mkdirSync(d,{recursive:!0});const g=m.map((e=>async function(e){const{fileUrl:t,savePath:r,token:o,key:n,fileName:a}=e;return s.get(t,{...T({token:o,key:n}),responseType:"stream"}).then((async e=>{if(e.request?.path?.startsWith("/login"))throw new Error(`"${a}" need token`);if(200===e.status){const o=f.createWriteStream(r);return e.data?.pipe(o),q(o).then((()=>({fileUrl:t,savePath:r})))}throw new Error(`response status ${e.status}`)}))}({fileUrl:e.url,savePath:e.currentFilePath,token:l,key:u,fileName:e.fileName}))),w=await Promise.all(g).finally((function(){p&&p.stop()}));let $=r;return w.forEach((e=>{const t=m.find((t=>t.url===e.fileUrl));if(t){const e=`[附件: ${t.fileName}](${n}/${t.fileName})`;$=$.replace(t.rawMd,e)}})),{mdData:$}}const q=d.promisify($.finished);async function A(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:s,key:l}=n,{bookId:u,itemUrl:h,savePath:p,saveFilePath:d,uuid:f,articleUrl:m,articleTitle:g,ignoreImg:$,host:k,imageServiceDomains:b}=r,v={articleUrl:h,bookId:u,token:s,host:k,key:l},{httpStatus:I,apiUrl:L,response:E}=await D(v),S=E?.data?.type?.toLocaleLowerCase();let P="";if(S===w.SHEET){const{response:e}=await D(v,!1);try{const t=e?.data?.content,r=t?JSON.parse(t):{},o=r?.sheet;P=o?U(o):""}catch(e){const t=y.get(S);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([w.BOARD,w.TABLE].includes(S)){const e=y.get(S);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof E?.data?.sourcecode)throw new Error(`download article Error: ${L}, http status ${I}`);P=E.data.sourcecode,P=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}(P)}const T=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}(P);if(T.length&&!$){const e=await D(v,!1);P=function(e,t,r){if(!r)return t;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,a=!0;for(;a||Boolean(s);)if(a=!1,s=o.exec(r),s?.[1])try{const e=decodeURIComponent(s[1]),t=JSON.parse(e);n.push(t?.src||"")}catch(e){n.push("")}const i=new Map;return e.forEach((e=>{const{origin:r,pathname:o}=new URL(e),s=`${r}${o}`,a=n.find(((e,t)=>{const r=new RegExp(`${s}.*?`).test(e);return r&&n.splice(t,1),r}));if(a){const r=new RegExp(e,"g"),o=i.get(e)||0;let n=0;t=t.replace(r,(e=>{let t=e;return n===o&&(t=a),n+=1,t})),i.set(e,o+1)}})),t}(T,P,e.response?.data?.content??"")}const N={toc:n.toc,articleTitle:g,articleUrl:m},O=[];try{o.pause(),console.log("");P=(await j({mdData:P,savePath:p,attachmentsDir:`./attachments/${f}`,articleTitle:g,token:s,key:l})).mdData}catch(e){O.push(`附件下载失败: ${e.message||"unknown error"}`)}finally{o.continue()}if(T.length&&!$){let t;o.pause(),console.log(""),"test"!==a.env.NODE_ENV&&(t=i({text:`下载 "${g}" 的图片中...`,stream:a.stdout}),t.start());let r=[],n=P;try{const e=await c.run(P,{dist:p,imgDir:`./img/${f}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:m||"",transform:e=>x(e,b)});r=e.errorInfo,n=e.data}catch(e){r=[e]}P=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.writeFile(d,F(P,N)),s(),new Error(`${o}`)}s()}try{if(await e.writeFile(d,F(P,N)),O.length>0)throw new Error(O[0]);return!0}catch(e){throw new Error(`${e.message}`)}}function F(e,t){const{articleTitle:r,articleUrl:o,toc:n}=t;let s=e;s=s.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((e,t,r)=>`| <br />- [${t}]${r}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),s=s.replace(/(\|?)(.*?)\|/gm,((e,t,r)=>`${t}${r.replace(/<br(\s?)\/>/gm,"")}|`)),s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const a=r?`# ${r}\n\n`:"";let i=n?l(s).content:"";i&&(i=`${i}\n\n---\n\n`);return s=`${a}${i}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}exports.logger=I,exports.main=async function(r,o){const{bookId:n,tocList:a,bookName:i,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:h}=await((e,t)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return s.get(e,T(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||b,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((()=>({})))})(r,{token:o.token,key:o.key});if(!n)throw new Error("No found book id");if(!a||0===a.length)throw new Error("No found toc list");const p=t.resolve(o.distDir,i?N(i):String(n));await e.mkdir(p,{recursive:!0});const d=a.length,f=new L(p,d);if(await f.init(),f.curr===d)return f.bar&&f.bar.stop(),void I.info(`√ 已完成: ${p}`);const m=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((e=>{m.set(e.toc.uuid,e)}));const $=r.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(r){const{articleUrlPrefix:o,total:n,uuidMap:s,tocList:a,bookPath:i,bookId:c,progressBar:l,host:u,options:h,imageServiceDomains:p=[]}=r;let d=0,f=0,m=0;const $=[],y=[];for(let t=0;t<n;t++){const r=a[t];if("string"!=typeof r.type)continue;if(s.get(r.uuid))continue;const o=r.type.toLocaleLowerCase();if(o===g.TITLE||""!==r.child_uuid||o===g.LINK){let t=r;const n=[],a=[];for(;t;)n.unshift(N(t.title)),a.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const c={path:n.map(N).join("/"),pathTitleList:n,pathIdList:a,toc:r};o===g.LINK?(m+=1,y.push(c)):await e.mkdir(`${i}/${n.map(N).join("/")}`,{recursive:!0}),s.set(r.uuid,c),o===w.DOC?await k(r):await l.updateProgress(c,o!==g.LINK)}else r.url&&await k(r)}async function k(e){f+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const n=e.type.toLocaleLowerCase();s.get(e.parent_uuid)&&(r=s.get(e.parent_uuid));const a=N(e.title),m=[...r.pathTitleList,a],g=[...r.pathIdList,e.uuid];let y=[...r.pathTitleList,`${a}.md`].map(N).join("/"),k=r.pathTitleList.map(N).join("/");n===w.DOC&&e.child_uuid&&(y=[...r.pathTitleList,a,"index.md"].map(N).join("/"),k=m.map(N).join("/"));const b={path:y,savePath:k,pathTitleList:m,pathIdList:g,toc:e};let v=!0;const I=`${o}/${e.url}`;try{const r={bookId:c,itemUrl:e.url,savePath:t.resolve(i,b.savePath),saveFilePath:t.resolve(i,b.path),uuid:e.uuid,articleUrl:I,articleTitle:e.title,ignoreImg:h.ignoreImg,host:u,imageServiceDomains:p};await A({articleInfo:r,progressBar:l,options:h})}catch(e){v=!1,d+=1,$.push({articleUrl:I,errItem:b,errMsg:e.message,err:e})}s.set(e.uuid,b),await l.updateProgress(b,v)}if(m>0){I.warn("该知识库存在以下外链文章");for(const e of y)I.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(d>0){I.error(`本次执行总数${f}篇,✕ 失败${d}篇`);for(const e of $)I.error(`《${e.errItem.path}》: ${e.articleUrl}`),e.errMsg.split("\n").forEach((e=>{I.error(`———— ✕ ${e}`)}));I.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:$,total:d,uuidMap:m,tocList:a,bookPath:p,bookId:n,progressBar:f,host:u,options:o,imageServiceDomains:h});const y=new S({bookPath:p,bookName:i,bookDesc:c,uuidMap:m});await y.genFile(),I.info(`√ 生成目录 ${t.resolve(p,"index.md")}`),f.curr===d&&I.info(`√ 已完成: ${p}`)};
|
|
1
|
+
"use strict";var e=require("node:fs/promises"),t=require("node:path"),r=require("rand-user-agent"),o=require("log4js"),n=require("cli-progress"),s=require("axios"),a=require("node:process"),i=require("ora"),c=require("pull-md-img"),l=require("markdown-toc"),u=require("pako"),h=require("node:crypto"),p=require("node:stream"),d=require("node:util"),f=require("node:fs");function m(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var g,w,k=m(p);!function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(g||(g={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(w||(w={}));const y=new Map([[w.BOARD,"画板类型"],[w.TABLE,"数据表类型"],[w.SHEET,"表格类型"],[w.DOC,"文档类型"]]),$="_yuque_session",b="https://www.yuque.com",v="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",E=(o.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),o.getLogger("yuque-dl"));class L{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,E.info("根据上次数据继续断点下载")),this.bar=new n.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},n.Presets.legacy),this.bar.start(this.total,this.curr))}async getProgress(){let t=[];try{const r=await e.readFile(this.progressFilePath,{encoding:"utf8"});t=JSON.parse(r)}catch(r){r&&"ENOENT"===r.code&&await e.writeFile(this.progressFilePath,JSON.stringify(t),{encoding:"utf8"})}return t}async updateProgress(t,r){this.curr!==this.total&&(this.curr=this.curr+1,r&&(this.progressInfo.push(t),await e.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 I({browser:e="chrome",os:t="mac os",device:o="desktop"}){o=o.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let n=r(o,e,t);if("chrome"===e)for(;n.includes("Chrome-Lighthouse")||n.includes("Gener8")||n.includes("HeadlessChrome")||n.includes("SMTBot");)n=r(o,e,t);if("safari"===e)for(;n.includes("Applebot");)n=r(o,e,t);return n}class P{constructor(e){this.summaryInfo=e}async genFile(){const{bookName:t,bookDesc:r,bookPath:o,uuidMap:n}=this.summaryInfo;let s=`# ${t}\n\n`;r&&(s+=`> ${r}\n\n`);let a=s;const i=[];n.forEach((e=>{const t=e.toc,r=t.parent_uuid,o=this.findTree(i,r),n={text:t.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:t.uuid,level:1,type:"link"},s=t.type.toLocaleLowerCase();s===g.TITLE||""!==t.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,i.push(n)),s===g.DOC&&(n.link=e.path)):(n.type="link",n.link=s===g.LINK?e.toc.url:e.path,"boolean"!=typeof o?(Array.isArray(o.children)||(o.children=[]),n.level=o.level+1,o.children.push(n)):(n.level=1,i.push(n)))}));a+=this.genSummaryContent(i,"");try{await e.writeFile(`${o}/index.md`,a)}catch(e){E.error("Generate Summary Error")}return a}genSummaryContent(e,t){for(const r of e){if(r.type===g.TITLE)if(r.link){const e=r.link?r.link.replace(/\s/g,"%20"):r.link;t+=`\n${"".padStart(r.level+1,"#")} [${r.text}](${e})\n\n`}else t+=`\n${"".padStart(r.level+1,"#")} ${r.text}\n\n`;else if(r.type===g.LINK){const e=r.link?r.link.replace(/\s/g,"%20"):r.link;t+=`- [${r.text}](${e})\n`}Array.isArray(r.children)&&(t+=this.genSummaryContent(r.children,""))}return t}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 S(e){const{key:t=$,token:r}=e,o={"user-agent":I({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${t}=${r};`),o}function T(e){return{headers:S(e),beforeRedirect:t=>{t.headers={...t?.headers||{},...S(e)}}}}const D=(e,t=!0)=>{const{articleUrl:r,bookId:o,token:n,key:a,host:i=b}=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}`,s.get(c,T({token:n,key:a})).then((({data:e,status:t})=>({apiUrl:c,httpStatus:t,response:e})))};function N(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const U=e=>{if(!e)return"";const t=u.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 a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let i=Array(n+1).fill(" ").map(((e,t)=>{const r=t%a.length;return a[r]})).join(" | ");i=`| |${i}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${i}\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 O(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=h.createHash("sha256");return t.update(`${v}${e}`),t.digest("hex")}(e)}`:e}const x=/\[(.*?)\]\((.*?)\)/g,C=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;async function R(e){const{mdData:r,savePath:o,attachmentsDir:n,articleTitle:c,token:l,key:u}=e,h=(r.match(x)||[]).filter((e=>C.test(e)));if(0===h.length)return{mdData:r};const p=i({text:`下载 "${c}" 的附件中...`,stream:a.stdout});"test"!==a.env.NODE_ENV&&p.start();const d=t.resolve(o,n),m=h.map((e=>function(e,r){const[,o,n]=C.exec(e)||[];if(!n)return!1;const s=o||n.split("/").at(-1);if(!s)return!1;const a=t.join(r,s);return{fileName:s,url:n,rawMd:e,currentFilePath:a}}(e,d))).filter((e=>!1!==e));f.mkdirSync(d,{recursive:!0});const g=m.map((e=>async function(e){const{fileUrl:t,savePath:r,token:o,key:n,fileName:a}=e;return s.get(t,{...T({token:o,key:n}),responseType:"stream"}).then((async e=>{if(e.request?.path?.startsWith("/login"))throw new Error(`"${a}" need token`);if(200===e.status){const o=f.createWriteStream(r);return e.data?.pipe(o),j(o).then((()=>({fileUrl:t,savePath:r})))}throw new Error(`response status ${e.status}`)}))}({fileUrl:e.url,savePath:e.currentFilePath,token:l,key:u,fileName:e.fileName}))),w=await Promise.all(g).finally((function(){p&&p.stop()}));let k=r;return w.forEach((e=>{const t=m.find((t=>t.url===e.fileUrl));if(t){const e=`[附件: ${t.fileName}](${n}/${t.fileName})`;k=k.replace(t.rawMd,e)}})),{mdData:k}}const j=d.promisify(k.finished);async function q(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:s,key:l}=n,{bookId:u,itemUrl:h,savePath:p,saveFilePath:d,uuid:f,articleUrl:m,articleTitle:g,ignoreImg:k,host:$,imageServiceDomains:b}=r,v={articleUrl:h,bookId:u,token:s,host:$,key:l},{httpStatus:E,apiUrl:L,response:I}=await D(v),P=I?.data?.type?.toLocaleLowerCase();let S="";if(P===w.SHEET){const{response:e}=await D(v,!1);try{const t=e?.data?.content,r=t?JSON.parse(t):{},o=r?.sheet;S=o?U(o):""}catch(e){const t=y.get(P);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([w.BOARD,w.TABLE].includes(P)){const e=y.get(P);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof I?.data?.sourcecode)throw new Error(`download article Error: ${L}, http status ${E}`);S=I.data.sourcecode,S=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}(S)}const T=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}(S);if(T.length&&!k){const e=await D(v,!1);S=function(e,t,r){if(!r)return t;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,a=!0;for(;a||Boolean(s);)if(a=!1,s=o.exec(r),s?.[1])try{const e=decodeURIComponent(s[1]),t=JSON.parse(e);n.push(t?.src||"")}catch(e){n.push("")}const i=new Map;return e.forEach((e=>{const{origin:r,pathname:o}=new URL(e),s=`${r}${o}`,a=n.find(((e,t)=>{const r=new RegExp(`${s}.*?`).test(e);return r&&n.splice(t,1),r}));if(a){const r=new RegExp(e,"g"),o=i.get(e)||0;let n=0;t=t.replace(r,(e=>{let t=e;return n===o&&(t=a),n+=1,t})),i.set(e,o+1)}})),t}(T,S,e.response?.data?.content??"")}const N={toc:n.toc,articleTitle:g,articleUrl:m},x=[];try{o.pause(),console.log("");S=(await R({mdData:S,savePath:p,attachmentsDir:`./attachments/${f}`,articleTitle:g,token:s,key:l})).mdData}catch(e){x.push(`附件下载失败: ${e.message||"unknown error"}`)}finally{o.continue()}if(T.length&&!k){let t;o.pause(),console.log(""),"test"!==a.env.NODE_ENV&&(t=i({text:`下载 "${g}" 的图片中...`,stream:a.stdout}),t.start());let r=[],n=S;try{const e=await c.run(S,{dist:p,imgDir:`./img/${f}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:m||"",transform:e=>O(e=e.replace("x-oss-process=image%2Fwatermark%2C",""),b)});r=e.errorInfo,n=e.data}catch(e){r=[e]}S=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.writeFile(d,F(S,N)),s(),new Error(`${o}`)}s()}try{if(await e.writeFile(d,F(S,N)),x.length>0)throw new Error(x[0]);return!0}catch(e){throw new Error(`${e.message}`)}}function F(e,t){const{articleTitle:r,articleUrl:o,toc:n}=t;let s=e;s=s.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((e,t,r)=>`| <br />- [${t}]${r}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),s=s.replace(/(\|?)(.*?)\|/gm,((e,t,r)=>`${t}${r.replace(/<br(\s?)\/>/gm,"")}|`)),s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const a=r?`# ${r}\n\n`:"";let i=n?l(s).content:"";i&&(i=`${i}\n\n---\n\n`);return s=`${a}${i}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}exports.logger=E,exports.main=async function(r,o){if(!function(e){if("function"==typeof URL.canParse)return URL.canParse(e);try{return new URL(e),!0}catch(e){return!1}}(r))throw new Error("Please enter a valid URL");const{bookId:n,tocList:a,bookName:i,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:h}=await((e,t)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return s.get(e,T(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||b,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((e=>{const t=e?.message??"";if(!t)throw new Error("unknown error");if(["getaddrinfo ENOTFOUND","read ECONNRESET","Client network socket disconnected before secure TLS connection was established"].some((e=>t.startsWith(e))))throw new Error("请检查网络(是否正常联网/是否开启了代理软件)");throw new Error(t)}))})(r,{token:o.token,key:o.key});if(!n)throw new Error("No found book id");if(!a||0===a.length)throw new Error("No found toc list");const p=t.resolve(o.distDir,i?N(i):String(n));await e.mkdir(p,{recursive:!0});const d=a.length,f=new L(p,d);if(await f.init(),f.curr===d)return f.bar&&f.bar.stop(),void E.info(`√ 已完成: ${p}`);const m=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((e=>{m.set(e.toc.uuid,e)}));const k=r.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(r){const{articleUrlPrefix:o,total:n,uuidMap:s,tocList:a,bookPath:i,bookId:c,progressBar:l,host:u,options:h,imageServiceDomains:p=[]}=r;let d=0,f=0,m=0;const k=[],y=[];for(let t=0;t<n;t++){const r=a[t];if("string"!=typeof r.type)continue;if(s.get(r.uuid))continue;const o=r.type.toLocaleLowerCase();if(o===g.TITLE||""!==r.child_uuid||o===g.LINK){let t=r;const n=[],a=[];for(;t;)n.unshift(N(t.title)),a.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const c={path:n.map(N).join("/"),pathTitleList:n,pathIdList:a,toc:r};o===g.LINK?(m+=1,y.push(c)):await e.mkdir(`${i}/${n.map(N).join("/")}`,{recursive:!0}),s.set(r.uuid,c),o===w.DOC?await $(r):await l.updateProgress(c,o!==g.LINK)}else r.url&&await $(r)}async function $(e){f+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const n=e.type.toLocaleLowerCase();s.get(e.parent_uuid)&&(r=s.get(e.parent_uuid));const a=N(e.title),m=[...r.pathTitleList,a],g=[...r.pathIdList,e.uuid];let y=[...r.pathTitleList,`${a}.md`].map(N).join("/"),$=r.pathTitleList.map(N).join("/");n===w.DOC&&e.child_uuid&&(y=[...r.pathTitleList,a,"index.md"].map(N).join("/"),$=m.map(N).join("/"));const b={path:y,savePath:$,pathTitleList:m,pathIdList:g,toc:e};let v=!0;const E=`${o}/${e.url}`;try{const r={bookId:c,itemUrl:e.url,savePath:t.resolve(i,b.savePath),saveFilePath:t.resolve(i,b.path),uuid:e.uuid,articleUrl:E,articleTitle:e.title,ignoreImg:h.ignoreImg,host:u,imageServiceDomains:p};await q({articleInfo:r,progressBar:l,options:h})}catch(e){v=!1,d+=1,k.push({articleUrl:E,errItem:b,errMsg:e.message,err:e})}s.set(e.uuid,b),await l.updateProgress(b,v)}if(m>0){E.warn("该知识库存在以下外链文章");for(const e of y)E.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(d>0){E.error(`本次执行总数${f}篇,✕ 失败${d}篇`);for(const e of k)E.error(`《${e.errItem.path}》: ${e.articleUrl}`),e.errMsg.split("\n").forEach((e=>{E.error(`———— ✕ ${e}`)}));E.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:k,total:d,uuidMap:m,tocList:a,bookPath:p,bookId:n,progressBar:f,host:u,options:o,imageServiceDomains:h});const y=new P({bookPath:p,bookName:i,bookDesc:c,uuidMap:m});await y.genFile(),E.info(`√ 生成目录 ${t.resolve(p,"index.md")}`),f.curr===d&&E.info(`√ 已完成: ${p}`)};
|
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-D4Xc6rpR.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"),require("node:stream"),require("node:util"),require("node:fs"),exports.main=e.main;
|
package/dist/es/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as o}from"node:fs";import{cac as t}from"cac";import e from"semver";import{m as n,l as i}from"./index-
|
|
1
|
+
import{readFileSync as o}from"node:fs";import{cac as t}from"cac";import e from"semver";import{m as n,l as i}from"./index-BYWftZWJ.js";import"rand-user-agent";import{mkdir as s,writeFile as r,access as a,readdir as c,stat as p}from"node:fs/promises";import"cli-progress";import{createServer as m}from"vitepress";import{resolve as d,sep as l,join as f}from"node:path";import"log4js";import"axios";import"node:process";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";import"node:stream";import"node:util";let u;async function w(o){const t=d(o);if(!await y(t))throw new Error("server root not found");await async function(o){const t=o.split(l).filter(Boolean).at(-1)||"yuque-dl",e=f(o,"/.vitepress");await s(e,{recursive:!0});const n=f(e,"config.ts"),i=await async function(o){const t=[],e=[".vitepress","img","index.md","progress.json","attachments"];let n=await c(o);n=n.filter((o=>!e.includes(o)));for(const e of n){const n=f(o,e);if((await p(n)).isDirectory()){const i=await y(f(n,"index.md")),s={text:e,collapsed:!0,items:await h(o,e)};i&&(s.link=`/${e}/`),t.push(s)}else t.push({text:e.slice(0,e.lastIndexOf(".")),link:`/${e}`})}return t}(o),a=`\n export default {\n title: "${t}",\n themeConfig: {\n search: {\n provider: 'local'\n },\n sidebar: ${JSON.stringify(i)}\n },\n vite: {\n optimizeDeps: {\n include: []\n }\n },\n markdown: {\n html: false\n }\n }\n `;await r(n,a)}(t);const e=async()=>{const t=await m(o,{},(async()=>(u||(u=(async()=>{await t.close(),await e()})().finally((()=>{u=void 0}))),u)));await t.listen(),t.printUrls()};await e().catch((o=>{console.error(o),process.exit(1)}))}async function y(o){try{return await a(o),!0}catch(o){if("ENOENT"===o.code)return!1;throw o}}async function h(o,...t){const e=await c(f(o,...t)),n=[];for(const i of e){const e=f(o,...t,i);if((await p(e)).isDirectory()){const s=await h(f(o),...t,i);if(s.length>0){const o={text:i,items:s,collapsed:false};await y(f(e,"index.md"))&&(o.link="/"+[...t,i].map(decodeURIComponent).join("/")+"/"),n.push(o)}}else{if("index.md"===i||/^-.*\.(md|MD)$/.test(i)||!i.endsWith(".md"))continue;const o=i.replace(/\.md$/,""),e={text:o,link:"/"+[...t.map(decodeURIComponent),`${encodeURI(o)}.html`].join("/")};n.push(e)}}return n}const k=t("yuque-dl"),{version:x,engines:g}=JSON.parse(o(new URL("../../package.json",import.meta.url)).toString());!function(){const o=g.node;e.satisfies(process.version,o)||(i.error(`✕ nodejs 版本需 ${o}, 当前版本为 ${process.version}`),process.exit(1))}(),k.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("--toc","是否输出文档toc目录",{default:!1}).action((async(o,t)=>{try{await n(o,t),process.exit(0)}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}})),k.command("server <serverPath>","启动web服务").action((async o=>{try{await w(o)}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}})),k.help(),k.version(x);try{k.parse()}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}
|
|
@@ -0,0 +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 a from"cli-progress";import i from"axios";import{stdout as c,env as l}from"node:process";import u from"ora";import h from"pull-md-img";import p from"markdown-toc";import d from"pako";import f from"node:crypto";import*as m from"node:stream";import{promisify as g}from"node:util";import{mkdirSync as w,createWriteStream as $}from"node:fs";var k,y;!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(k||(k={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(y||(y={}));const b=new Map([[y.BOARD,"画板类型"],[y.TABLE,"数据表类型"],[y.SHEET,"表格类型"],[y.DOC,"文档类型"]]),L="_yuque_session",E="https://www.yuque.com",v="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",I=(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 T{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,I.info("根据上次数据继续断点下载")),this.bar=new a.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},a.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 P({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 S{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 a=s;const i=[];n.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(i,r),n={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:"link"},s=e.type.toLocaleLowerCase();s===k.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,i.push(n)),s===k.DOC&&(n.link=t.path)):(n.type="link",n.link=s===k.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,i.push(n)))}));a+=this.genSummaryContent(i,"");try{await t.writeFile(`${o}/index.md`,a)}catch(t){I.error("Generate Summary Error")}return a}genSummaryContent(t,e){for(const r of t){if(r.type===k.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===k.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 D(t){const{key:e=L,token:r}=t,o={"user-agent":P({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function N(t){return{headers:D(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...D(t)}}}}const U=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:n,key:s,host:a=E}=t;let c=`${a}/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}`,i.get(c,N({token:n,key:s})).then((({data:t,status:e})=>({apiUrl:c,httpStatus:e,response:t})))};function x(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const C=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 a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let i=Array(n+1).fill(" ").map(((t,e)=>{const r=e%a.length;return a[r]})).join(" | ");i=`| |${i}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${i}\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 O(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(`${v}${t}`),e.digest("hex")}(t)}`:t}const R=/\[(.*?)\]\((.*?)\)/g,A=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;async function F(t){const{mdData:e,savePath:r,attachmentsDir:n,articleTitle:s,token:a,key:h}=t,p=(e.match(R)||[]).filter((t=>A.test(t)));if(0===p.length)return{mdData:e};const d=u({text:`下载 "${s}" 的附件中...`,stream:c});"test"!==l.NODE_ENV&&d.start();const f=o.resolve(r,n),m=p.map((t=>function(t,e){const[,r,n]=A.exec(t)||[];if(!n)return!1;const s=r||n.split("/").at(-1);if(!s)return!1;const a=o.join(e,s);return{fileName:s,url:n,rawMd:t,currentFilePath:a}}(t,f))).filter((t=>!1!==t));w(f,{recursive:!0});const g=m.map((t=>async function(t){const{fileUrl:e,savePath:r,token:o,key:n,fileName:s}=t;return i.get(e,{...N({token:o,key:n}),responseType:"stream"}).then((async t=>{if(t.request?.path?.startsWith("/login"))throw new Error(`"${s}" need token`);if(200===t.status){const o=$(r);return t.data?.pipe(o),B(o).then((()=>({fileUrl:e,savePath:r})))}throw new Error(`response status ${t.status}`)}))}({fileUrl:t.url,savePath:t.currentFilePath,token:a,key:h,fileName:t.fileName}))),k=await Promise.all(g).finally((function(){d&&d.stop()}));let y=e;return k.forEach((t=>{const e=m.find((e=>e.url===t.fileUrl));if(e){const t=`[附件: ${e.fileName}](${n}/${e.fileName})`;y=y.replace(e.rawMd,t)}})),{mdData:y}}const B=g(m.finished);async function j(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:s,key:a}=n,{bookId:i,itemUrl:p,savePath:d,saveFilePath:f,uuid:m,articleUrl:g,articleTitle:w,ignoreImg:$,host:k,imageServiceDomains:L}=r,E={articleUrl:p,bookId:i,token:s,host:k,key:a},{httpStatus:v,apiUrl:I,response:T}=await U(E),P=T?.data?.type?.toLocaleLowerCase();let S="";if(P===y.SHEET){const{response:t}=await U(E,!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;S=o?C(o):""}catch(t){const e=b.get(P);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([y.BOARD,y.TABLE].includes(P)){const t=b.get(P);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof T?.data?.sourcecode)throw new Error(`download article Error: ${I}, http status ${v}`);S=T.data.sourcecode,S=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}(S)}const D=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}(S);if(D.length&&!$){const t=await U(E,!1);S=function(t,e,r){if(!r)return e;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,a=!0;for(;a||Boolean(s);)if(a=!1,s=o.exec(r),s?.[1])try{const t=decodeURIComponent(s[1]),e=JSON.parse(t);n.push(e?.src||"")}catch(t){n.push("")}const i=new Map;return t.forEach((t=>{const{origin:r,pathname:o}=new URL(t),s=`${r}${o}`,a=n.find(((t,e)=>{const r=new RegExp(`${s}.*?`).test(t);return r&&n.splice(e,1),r}));if(a){const r=new RegExp(t,"g"),o=i.get(t)||0;let n=0;e=e.replace(r,(t=>{let e=t;return n===o&&(e=a),n+=1,e})),i.set(t,o+1)}})),e}(D,S,t.response?.data?.content??"")}const N={toc:n.toc,articleTitle:w,articleUrl:g},x=[];try{o.pause(),console.log("");S=(await F({mdData:S,savePath:d,attachmentsDir:`./attachments/${m}`,articleTitle:w,token:s,key:a})).mdData}catch(t){x.push(`附件下载失败: ${t.message||"unknown error"}`)}finally{o.continue()}if(D.length&&!$){let t;o.pause(),console.log(""),"test"!==l.NODE_ENV&&(t=u({text:`下载 "${w}" 的图片中...`,stream:c}),t.start());let r=[],n=S;try{const t=await h.run(S,{dist:d,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:g||"",transform:t=>O(t=t.replace("x-oss-process=image%2Fwatermark%2C",""),L)});r=t.errorInfo,n=t.data}catch(t){r=[t]}S=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,M(S,N)),s(),new Error(`${o}`)}s()}try{if(await e(f,M(S,N)),x.length>0)throw new Error(x[0]);return!0}catch(t){throw new Error(`${t.message}`)}}function M(t,e){const{articleTitle:r,articleUrl:o,toc:n}=e;let s=t;s=s.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((t,e,r)=>`| <br />- [${e}]${r}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),s=s.replace(/(\|?)(.*?)\|/gm,((t,e,r)=>`${e}${r.replace(/<br(\s?)\/>/gm,"")}|`)),s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const a=r?`# ${r}\n\n`:"";let i=n?p(s).content:"";i&&(i=`${i}\n\n---\n\n`);return s=`${a}${i}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}async function _(t,e){if(!function(t){if("function"==typeof URL.canParse)return URL.canParse(t);try{return new URL(t),!0}catch(t){return!1}}(t))throw new Error("Please enter a valid URL");const{bookId:n,tocList:s,bookName:a,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:h}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return i.get(t,N(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||E,imageServiceDomains:o.imageServiceDomains||[]}:{}})).catch((t=>{const e=t?.message??"";if(!e)throw new Error("unknown error");if(["getaddrinfo ENOTFOUND","read ECONNRESET","Client network socket disconnected before secure TLS connection was established"].some((t=>e.startsWith(t))))throw new Error("请检查网络(是否正常联网/是否开启了代理软件)");throw new Error(e)}))})(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 p=o.resolve(e.distDir,a?x(a):String(n));await r(p,{recursive:!0});const d=s.length,f=new T(p,d);if(await f.init(),f.curr===d)return f.bar&&f.bar.stop(),void I.info(`√ 已完成: ${p}`);const m=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((t=>{m.set(t.toc.uuid,t)}));const g=t.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:n,uuidMap:s,tocList:a,bookPath:i,bookId:c,progressBar:l,host:u,options:h,imageServiceDomains:p=[]}=t;let d=0,f=0,m=0;const g=[],w=[];for(let t=0;t<n;t++){const e=a[t];if("string"!=typeof e.type)continue;if(s.get(e.uuid))continue;const o=e.type.toLocaleLowerCase();if(o===k.TITLE||""!==e.child_uuid||o===k.LINK){let t=e;const n=[],a=[];for(;t;)n.unshift(x(t.title)),a.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const c={path:n.map(x).join("/"),pathTitleList:n,pathIdList:a,toc:e};o===k.LINK?(m+=1,w.push(c)):await r(`${i}/${n.map(x).join("/")}`,{recursive:!0}),s.set(e.uuid,c),o===y.DOC?await $(e):await l.updateProgress(c,o!==k.LINK)}else e.url&&await $(e)}async function $(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 a=x(t.title),m=[...r.pathTitleList,a],w=[...r.pathIdList,t.uuid];let $=[...r.pathTitleList,`${a}.md`].map(x).join("/"),k=r.pathTitleList.map(x).join("/");n===y.DOC&&t.child_uuid&&($=[...r.pathTitleList,a,"index.md"].map(x).join("/"),k=m.map(x).join("/"));const b={path:$,savePath:k,pathTitleList:m,pathIdList:w,toc:t};let L=!0;const E=`${e}/${t.url}`;try{const e={bookId:c,itemUrl:t.url,savePath:o.resolve(i,b.savePath),saveFilePath:o.resolve(i,b.path),uuid:t.uuid,articleUrl:E,articleTitle:t.title,ignoreImg:h.ignoreImg,host:u,imageServiceDomains:p};await j({articleInfo:e,progressBar:l,options:h})}catch(t){L=!1,d+=1,g.push({articleUrl:E,errItem:b,errMsg:t.message,err:t})}s.set(t.uuid,b),await l.updateProgress(b,L)}if(m>0){I.warn("该知识库存在以下外链文章");for(const t of w)I.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(d>0){I.error(`本次执行总数${f}篇,✕ 失败${d}篇`);for(const t of g)I.error(`《${t.errItem.path}》: ${t.articleUrl}`),t.errMsg.split("\n").forEach((t=>{I.error(`———— ✕ ${t}`)}));I.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:g,total:d,uuidMap:m,tocList:s,bookPath:p,bookId:n,progressBar:f,host:u,options:e,imageServiceDomains:h});const w=new S({bookPath:p,bookName:a,bookDesc:c,uuidMap:m});await w.genFile(),I.info(`√ 生成目录 ${o.resolve(p,"index.md")}`),f.curr===d&&I.info(`√ 已完成: ${p}`)}export{I as l,_ 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-BYWftZWJ.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";import"node:stream";import"node:util";import"node:fs";
|
package/package.json
CHANGED
package/types/utils/index.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ declare function randUserAgent({ browser, os, device }: {
|
|
|
9
9
|
*/
|
|
10
10
|
declare function getMarkdownImageList(mdStr: string): string[];
|
|
11
11
|
declare function removeEmojis(dirName: string): string;
|
|
12
|
-
|
|
12
|
+
declare function isValidUrl(url: string): boolean;
|
|
13
|
+
export { randUserAgent, getMarkdownImageList, removeEmojis, isValidUrl };
|
|
13
14
|
export * from './log';
|
|
14
15
|
export * from './ProgressBar';
|
|
@@ -1 +0,0 @@
|
|
|
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 a from"cli-progress";import i from"axios";import{stdout as c,env as l}from"node:process";import u from"ora";import h from"pull-md-img";import p from"markdown-toc";import d from"pako";import f from"node:crypto";import*as m from"node:stream";import{promisify as g}from"node:util";import{mkdirSync as w,createWriteStream as $}from"node:fs";var y,k;!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(y||(y={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(k||(k={}));const b=new Map([[k.BOARD,"画板类型"],[k.TABLE,"数据表类型"],[k.SHEET,"表格类型"],[k.DOC,"文档类型"]]),I="_yuque_session",v="https://www.yuque.com",L="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",E=(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 S{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,E.info("根据上次数据继续断点下载")),this.bar=new a.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},a.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 T({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 P{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 a=s;const i=[];n.forEach((t=>{const e=t.toc,r=e.parent_uuid,o=this.findTree(i,r),n={text:e.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:e.uuid,level:1,type:"link"},s=e.type.toLocaleLowerCase();s===y.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,i.push(n)),s===y.DOC&&(n.link=t.path)):(n.type="link",n.link=s===y.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,i.push(n)))}));a+=this.genSummaryContent(i,"");try{await t.writeFile(`${o}/index.md`,a)}catch(t){E.error("Generate Summary Error")}return a}genSummaryContent(t,e){for(const r of t){if(r.type===y.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===y.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 D(t){const{key:e=I,token:r}=t,o={"user-agent":T({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function N(t){return{headers:D(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...D(t)}}}}const U=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:n,key:s,host:a=v}=t;let c=`${a}/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}`,i.get(c,N({token:n,key:s})).then((({data:t,status:e})=>({apiUrl:c,httpStatus:e,response:t})))};function x(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const C=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 a="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let i=Array(n+1).fill(" ").map(((t,e)=>{const r=e%a.length;return a[r]})).join(" | ");i=`| |${i}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,s=`${i}\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 O(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(`${L}${t}`),e.digest("hex")}(t)}`:t}const A=/\[(.*?)\]\((.*?)\)/g,B=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;async function R(t){const{mdData:e,savePath:r,attachmentsDir:n,articleTitle:s,token:a,key:h}=t,p=(e.match(A)||[]).filter((t=>B.test(t)));if(0===p.length)return{mdData:e};const d=u({text:`下载 "${s}" 的附件中...`,stream:c});"test"!==l.NODE_ENV&&d.start();const f=o.resolve(r,n),m=p.map((t=>function(t,e){const[,r,n]=B.exec(t)||[];if(!n)return!1;const s=r||n.split("/").at(-1);if(!s)return!1;const a=o.join(e,s);return{fileName:s,url:n,rawMd:t,currentFilePath:a}}(t,f))).filter((t=>!1!==t));w(f,{recursive:!0});const g=m.map((t=>async function(t){const{fileUrl:e,savePath:r,token:o,key:n,fileName:s}=t;return i.get(e,{...N({token:o,key:n}),responseType:"stream"}).then((async t=>{if(t.request?.path?.startsWith("/login"))throw new Error(`"${s}" need token`);if(200===t.status){const o=$(r);return t.data?.pipe(o),j(o).then((()=>({fileUrl:e,savePath:r})))}throw new Error(`response status ${t.status}`)}))}({fileUrl:t.url,savePath:t.currentFilePath,token:a,key:h,fileName:t.fileName}))),y=await Promise.all(g).finally((function(){d&&d.stop()}));let k=e;return y.forEach((t=>{const e=m.find((e=>e.url===t.fileUrl));if(e){const t=`[附件: ${e.fileName}](${n}/${e.fileName})`;k=k.replace(e.rawMd,t)}})),{mdData:k}}const j=g(m.finished);async function F(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:s,key:a}=n,{bookId:i,itemUrl:p,savePath:d,saveFilePath:f,uuid:m,articleUrl:g,articleTitle:w,ignoreImg:$,host:y,imageServiceDomains:I}=r,v={articleUrl:p,bookId:i,token:s,host:y,key:a},{httpStatus:L,apiUrl:E,response:S}=await U(v),T=S?.data?.type?.toLocaleLowerCase();let P="";if(T===k.SHEET){const{response:t}=await U(v,!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;P=o?C(o):""}catch(t){const e=b.get(T);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([k.BOARD,k.TABLE].includes(T)){const t=b.get(T);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof S?.data?.sourcecode)throw new Error(`download article Error: ${E}, http status ${L}`);P=S.data.sourcecode,P=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}(P)}const D=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}(P);if(D.length&&!$){const t=await U(v,!1);P=function(t,e,r){if(!r)return e;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let s,a=!0;for(;a||Boolean(s);)if(a=!1,s=o.exec(r),s?.[1])try{const t=decodeURIComponent(s[1]),e=JSON.parse(t);n.push(e?.src||"")}catch(t){n.push("")}const i=new Map;return t.forEach((t=>{const{origin:r,pathname:o}=new URL(t),s=`${r}${o}`,a=n.find(((t,e)=>{const r=new RegExp(`${s}.*?`).test(t);return r&&n.splice(e,1),r}));if(a){const r=new RegExp(t,"g"),o=i.get(t)||0;let n=0;e=e.replace(r,(t=>{let e=t;return n===o&&(e=a),n+=1,e})),i.set(t,o+1)}})),e}(D,P,t.response?.data?.content??"")}const N={toc:n.toc,articleTitle:w,articleUrl:g},x=[];try{o.pause(),console.log("");P=(await R({mdData:P,savePath:d,attachmentsDir:`./attachments/${m}`,articleTitle:w,token:s,key:a})).mdData}catch(t){x.push(`附件下载失败: ${t.message||"unknown error"}`)}finally{o.continue()}if(D.length&&!$){let t;o.pause(),console.log(""),"test"!==l.NODE_ENV&&(t=u({text:`下载 "${w}" 的图片中...`,stream:c}),t.start());let r=[],n=P;try{const t=await h.run(P,{dist:d,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:g||"",transform:t=>O(t,I)});r=t.errorInfo,n=t.data}catch(t){r=[t]}P=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,M(P,N)),s(),new Error(`${o}`)}s()}try{if(await e(f,M(P,N)),x.length>0)throw new Error(x[0]);return!0}catch(t){throw new Error(`${t.message}`)}}function M(t,e){const{articleTitle:r,articleUrl:o,toc:n}=e;let s=t;s=s.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((t,e,r)=>`| <br />- [${e}]${r}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),s=s.replace(/(\|?)(.*?)\|/gm,((t,e,r)=>`${e}${r.replace(/<br(\s?)\/>/gm,"")}|`)),s=s.replace(/<br(\s?)\/>/gm,"\n"),s=s.replace(/<a.*?>(\s*?)<\/a>/gm,"");const a=r?`# ${r}\n\n`:"";let i=n?p(s).content:"";i&&(i=`${i}\n\n---\n\n`);return s=`${a}${i}${s}${o?`\n\n> 原文: <${o}>`:""}`,s}async function _(t,e){const{bookId:n,tocList:s,bookName:a,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:h}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return i.get(t,N(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||v,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 p=o.resolve(e.distDir,a?x(a):String(n));await r(p,{recursive:!0});const d=s.length,f=new S(p,d);if(await f.init(),f.curr===d)return f.bar&&f.bar.stop(),void E.info(`√ 已完成: ${p}`);const m=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((t=>{m.set(t.toc.uuid,t)}));const g=t.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:n,uuidMap:s,tocList:a,bookPath:i,bookId:c,progressBar:l,host:u,options:h,imageServiceDomains:p=[]}=t;let d=0,f=0,m=0;const g=[],w=[];for(let t=0;t<n;t++){const e=a[t];if("string"!=typeof e.type)continue;if(s.get(e.uuid))continue;const o=e.type.toLocaleLowerCase();if(o===y.TITLE||""!==e.child_uuid||o===y.LINK){let t=e;const n=[],a=[];for(;t;)n.unshift(x(t.title)),a.unshift(t.uuid),t=s.get(t.parent_uuid)?s.get(t.parent_uuid).toc:void 0;const c={path:n.map(x).join("/"),pathTitleList:n,pathIdList:a,toc:e};o===y.LINK?(m+=1,w.push(c)):await r(`${i}/${n.map(x).join("/")}`,{recursive:!0}),s.set(e.uuid,c),o===k.DOC?await $(e):await l.updateProgress(c,o!==y.LINK)}else e.url&&await $(e)}async function $(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 a=x(t.title),m=[...r.pathTitleList,a],w=[...r.pathIdList,t.uuid];let $=[...r.pathTitleList,`${a}.md`].map(x).join("/"),y=r.pathTitleList.map(x).join("/");n===k.DOC&&t.child_uuid&&($=[...r.pathTitleList,a,"index.md"].map(x).join("/"),y=m.map(x).join("/"));const b={path:$,savePath:y,pathTitleList:m,pathIdList:w,toc:t};let I=!0;const v=`${e}/${t.url}`;try{const e={bookId:c,itemUrl:t.url,savePath:o.resolve(i,b.savePath),saveFilePath:o.resolve(i,b.path),uuid:t.uuid,articleUrl:v,articleTitle:t.title,ignoreImg:h.ignoreImg,host:u,imageServiceDomains:p};await F({articleInfo:e,progressBar:l,options:h})}catch(t){I=!1,d+=1,g.push({articleUrl:v,errItem:b,errMsg:t.message,err:t})}s.set(t.uuid,b),await l.updateProgress(b,I)}if(m>0){E.warn("该知识库存在以下外链文章");for(const t of w)E.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(d>0){E.error(`本次执行总数${f}篇,✕ 失败${d}篇`);for(const t of g)E.error(`《${t.errItem.path}》: ${t.articleUrl}`),t.errMsg.split("\n").forEach((t=>{E.error(`———— ✕ ${t}`)}));E.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:g,total:d,uuidMap:m,tocList:s,bookPath:p,bookId:n,progressBar:f,host:u,options:e,imageServiceDomains:h});const w=new P({bookPath:p,bookName:a,bookDesc:c,uuidMap:m});await w.genFile(),E.info(`√ 生成目录 ${o.resolve(p,"index.md")}`),f.curr===d&&E.info(`√ 已完成: ${p}`)}export{E as l,_ as m};
|