yuque-dl 1.0.68 → 1.0.69

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/bin/index.js CHANGED
@@ -1,6 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  function run() {
4
- return import('../dist/es/cli.js')
4
+ return import('../dist/es/cli.js').catch((e) => {
5
+ const lowVersionError = [
6
+ 'Not supported',
7
+ 'No such built-in module: node:fs/promises',
8
+ 'Only file and data URLs are supported by the default ESM loader',
9
+ // at Loader.moduleStrategy (internal/modules/esm/translators.js:145:18)
10
+ 'Unexpected token \'??=\''
11
+ ]
12
+ if (lowVersionError.includes(e.message)) {
13
+ console.error('\x1b[31m%s\x1b[0m', '✕ nodejs版本过低')
14
+ return
15
+ }
16
+ throw e
17
+ })
5
18
  }
6
19
  run()
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-CIP6WwpQ.js";import"rand-user-agent";import{mkdir as r,writeFile as s,access as a,readdir as c,stat as m}from"node:fs/promises";import"cli-progress";import{createServer as p}from"vitepress";import{resolve as d,sep as l,join as f}from"node:path";import"log4js";import"node:process";import"axios";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";import"node:stream";import"node:util";import"mdast-util-from-markdown";import"mdast-util-to-markdown";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 r(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 m(n)).isDirectory()){const i=await y(f(n,"index.md")),r={text:e,collapsed:!0,items:await k(o,e)};i&&(r.link=`/${e}/`),t.push(r)}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 s(n,a)}(t);const e=async()=>{const t=await p(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 k(o,...t){const e=await c(f(o,...t)),n=[];for(const i of e){const e=f(o,...t,i);if((await m(e)).isDirectory()){const r=await k(f(o),...t,i);if(r.length>0){const o={text:i,items:r,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 h=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))}(),h.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)}})),h.command("server <serverPath>","启动web服务").action((async o=>{try{await w(o)}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}})),h.help(),h.version(x);try{h.parse()}catch(o){i.error(o.message||"unknown exception"),process.exit(1)}
1
+ import{_ as o,l as e,m as i}from"./index-DT4ximDd.js";import{readFileSync as t}from"node:fs";import{cac as n}from"cac";import r from"semver";import"rand-user-agent";import{mkdir as s,writeFile as d,access as c,readdir as l,stat as m}from"node:fs/promises";import"cli-progress";import{createServer as p}from"vitepress";import{resolve as a,sep as u,join as f}from"node:path";import"log4js";import"node:process";import"axios";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";import"node:stream";import"node:util";import"mdast-util-from-markdown";import"mdast-util-to-markdown";let y;function v(e){return o(this,void 0,void 0,(function*(){const i=a(e);if(!(yield h(i)))throw new Error("server root not found");yield function(e){return o(this,void 0,void 0,(function*(){const i=e.split(u).filter(Boolean).at(-1)||"yuque-dl",t=f(e,"/.vitepress");yield s(t,{recursive:!0});const n=f(t,"config.ts"),r=yield function(e){return o(this,void 0,void 0,(function*(){const o=[],i=[".vitepress","img","index.md","progress.json","attachments"];let t=yield l(e);t=t.filter((o=>!i.includes(o)));for(const i of t){const t=f(e,i);if((yield m(t)).isDirectory()){const n=yield h(f(t,"index.md")),r={text:i,collapsed:!0,items:yield k(e,i)};n&&(r.link=`/${i}/`),o.push(r)}else o.push({text:i.slice(0,i.lastIndexOf(".")),link:`/${i}`})}return o}))}(e),c=`\n export default {\n title: "${i}",\n themeConfig: {\n search: {\n provider: 'local'\n },\n sidebar: ${JSON.stringify(r)}\n },\n vite: {\n optimizeDeps: {\n include: []\n }\n },\n markdown: {\n html: false\n }\n }\n `;yield d(n,c)}))}(i);const t=()=>o(this,void 0,void 0,(function*(){const i=yield p(e,{},(()=>o(this,void 0,void 0,(function*(){return y||(y=(()=>o(this,void 0,void 0,(function*(){yield i.close(),yield t()})))().finally((()=>{y=void 0}))),y}))));yield i.listen(),i.printUrls()}));yield t().catch((o=>{console.error(o),process.exit(1)}))}))}function h(e){return o(this,void 0,void 0,(function*(){try{return yield c(e),!0}catch(o){if("ENOENT"===o.code)return!1;throw o}}))}function k(e,...i){return o(this,void 0,void 0,(function*(){const o=yield l(f(e,...i)),t=[];for(const n of o){const o=f(e,...i,n);if((yield m(o)).isDirectory()){const r=yield k(f(e),...i,n);if(r.length>0){const e={text:n,items:r,collapsed:false};(yield h(f(o,"index.md")))&&(e.link="/"+[...i,n].map(decodeURIComponent).join("/")+"/"),t.push(e)}}else{if("index.md"===n||/^-.*\.(md|MD)$/.test(n)||!n.endsWith(".md"))continue;const o=n.replace(/\.md$/,""),e={text:o,link:"/"+[...i.map(decodeURIComponent),`${encodeURI(o)}.html`].join("/")};t.push(e)}}return t}))}const x=n("yuque-dl"),{version:g,engines:w}=JSON.parse(t(new URL("../../package.json",import.meta.url)).toString());!function(){const o=w.node;r.satisfies(process.version,o)||(e.error(`✕ nodejs 版本需 ${o}, 当前版本为 ${process.version}`),process.exit(1))}(),x.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(((t,n)=>o(void 0,void 0,void 0,(function*(){try{yield i(t,n),process.exit(0)}catch(o){e.error(o.message||"unknown exception"),process.exit(1)}})))),x.command("server <serverPath>","启动web服务").action((i=>o(void 0,void 0,void 0,(function*(){try{yield v(i)}catch(o){e.error(o.message||"unknown exception"),process.exit(1)}})))),x.help(),x.version(g);try{x.parse()}catch(o){e.error(o.message||"unknown exception"),process.exit(1)}
@@ -0,0 +1 @@
1
+ import e,{writeFile as t,mkdir as o}from"node:fs/promises";import r from"node:path";import n from"rand-user-agent";import i from"log4js";import s from"cli-progress";import{env as a,stdout as l}from"node:process";import c from"axios";import u from"ora";import d from"pull-md-img";import h from"markdown-toc";import f from"pako";import p from"node:crypto";import{createWriteStream as m,mkdirSync as v}from"node:fs";import*as g from"node:stream";import{promisify as y}from"node:util";import{fromMarkdown as k}from"mdast-util-from-markdown";import{toMarkdown as $}from"mdast-util-to-markdown";function w(e,t,o,r){return new(o||(o=Promise))((function(n,i){function s(e){try{l(r.next(e))}catch(e){i(e)}}function a(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof o?t:new o((function(e){e(t)}))).then(s,a)}l((r=r.apply(e,t||[])).next())}))}var b,I;"function"==typeof SuppressedError&&SuppressedError,function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(b||(b={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(I||(I={}));const E=new Map([[I.BOARD,"画板类型"],[I.TABLE,"数据表类型"],[I.SHEET,"表格类型"],[I.DOC,"文档类型"]]),N="_yuque_session",P="https://www.yuque.com",L="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",D=(i.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),i.getLogger("yuque-dl"));class S{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}init(){return w(this,void 0,void 0,(function*(){this.progressInfo=yield this.getProgress(),this.curr=this.progressInfo.length,this.curr!==this.total&&(this.curr>0&&this.curr!==this.total&&(this.isDownloadInterrupted=!0,D.info("根据上次数据继续断点下载")),this.bar=new s.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},s.Presets.legacy),this.bar.start(this.total,this.curr))}))}getProgress(){return w(this,void 0,void 0,(function*(){let t=[];try{const o=yield e.readFile(this.progressFilePath,{encoding:"utf8"});t=JSON.parse(o)}catch(o){o&&"ENOENT"===o.code&&(yield e.writeFile(this.progressFilePath,JSON.stringify(t),{encoding:"utf8"}))}return t}))}updateProgress(t,o){return w(this,void 0,void 0,(function*(){this.curr!==this.total&&(this.curr=this.curr+1,o&&(this.progressInfo.push(t),yield 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(){var e;this.clearLine(2),null===(e=this.bar)||void 0===e||e.start(this.total,this.curr)}clearLine(e){var t;if(!(e<=0)&&"function"==typeof(null===(t=null===process||void 0===process?void 0:process.stderr)||void 0===t?void 0:t.cursorTo)){process.stderr.cursorTo(0);for(let t=0;t<e;t++)process.stderr.moveCursor(0,-1),process.stderr.clearLine(1)}}}function T({browser:e="chrome",os:t="mac os",device:o="desktop"}){o=o.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let r=n(o,e,t);if("chrome"===e)for(;r.includes("Chrome-Lighthouse")||r.includes("Gener8")||r.includes("HeadlessChrome")||r.includes("SMTBot");)r=n(o,e,t);if("safari"===e)for(;r.includes("Applebot");)r=n(o,e,t);return r}function U(e){return e.toString().padStart(2,"0")}function O(e){const t=new Date(e);if(isNaN(t.getTime()))return"";const o=t.getFullYear(),r=t.getMonth()+1,n=t.getDate(),i=t.getHours(),s=t.getMinutes(),a=t.getSeconds();return`${o}-${U(r)}-${U(n)} ${U(i)}:${U(s)}:${U(a)}`}class x{constructor(e){this.summaryInfo=e}genFile(){return w(this,void 0,void 0,(function*(){const{bookName:t,bookDesc:o,bookPath:r,uuidMap:n}=this.summaryInfo;let i=`# ${t}\n\n`;o&&(i+=`> ${o}\n\n`);let s=i;const a=[];n.forEach((e=>{const t=e.toc,o=t.parent_uuid,r=this.findTree(a,o),n={text:t.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:t.uuid,level:1,type:"link"},i=t.type.toLocaleLowerCase();i===b.TITLE||""!==t.child_uuid?(n.type="title","boolean"!=typeof r?(Array.isArray(r.children)||(r.children=[]),n.level=r.level+1,r.children.push(n)):(n.level=1,a.push(n)),i===b.DOC&&(n.link=e.path)):(n.type="link",n.link=i===b.LINK?e.toc.url:e.path,"boolean"!=typeof r?(Array.isArray(r.children)||(r.children=[]),n.level=r.level+1,r.children.push(n)):(n.level=1,a.push(n)))}));s+=this.genSummaryContent(a,"");try{yield e.writeFile(`${r}/index.md`,s)}catch(e){D.error("Generate Summary Error")}return s}))}genSummaryContent(e,t){for(const o of e){if(o.type===b.TITLE)if(o.link){const e=o.link?o.link.replace(/\s/g,"%20"):o.link;t+=`\n${"".padStart(o.level+1,"#")} [${o.text}](${e})\n\n`}else t+=`\n${"".padStart(o.level+1,"#")} ${o.text}\n\n`;else if(o.type===b.LINK){const e=o.link?o.link.replace(/\s/g,"%20"):o.link;t+=`- [${o.text}](${e})\n`}Array.isArray(o.children)&&(t+=this.genSummaryContent(o.children,""))}return t}findIdItem(e,t){if(e.id===t)return e;if(e.children){const o=this.findTree(e.children,t);if(o)return o}return!1}findTree(e,t){if(!t)return!1;for(const o of e){const e=this.findIdItem(o,t);if(e)return e}return!1}}function C(e){const{key:t=N,token:o}=e,r={"user-agent":T({browser:"chrome",device:"desktop"})};return o&&(r.cookie=`${t}=${o};`),r}function j(e){const t={headers:C(e),beforeRedirect:t=>{t.headers=Object.assign(Object.assign({},(null==t?void 0:t.headers)||{}),C(e))}};return"test"===a.NODE_ENV&&(t.proxy=!1),t}const R=(e,t=!0)=>{const{articleUrl:o,bookId:r,token:n,key:i,host:s=P}=e;let a=`${s}/api/docs/${o}`;const l={book_id:String(r),merge_dynamic_data:String(!1)};t&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return a=`${a}?${u}`,c.get(a,j({token:n,key:i})).then((({data:e,status:t})=>({apiUrl:a,httpStatus:t,response:e})))};function _(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const F=e=>{if(!e)return"";const t=f.inflate(e,{to:"string"}),o=JSON.parse(t);let r="";return o.forEach((e=>{const t=`## ${e.name}\n`,o=function(e){var t,o,r;let n=Object.keys(e);n=n.filter((t=>Object.keys(e[t]).some((o=>{var r,n;return null===(n=null===(r=null==e?void 0:e[t])||void 0===r?void 0:r[o])||void 0===n?void 0:n.v}))));let i=[];n.forEach((t=>{const o=e[t];o&&(i=i.concat(Object.keys(o)))}));const s=Math.max(...n.map((e=>Number(e)))),a=Math.max(...i.map((e=>Number(e))));if(s<0||a<0)return"";let l="";const c="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let u=Array(a+1).fill(" ").map(((e,t)=>{const o=t%c.length;return c[o]})).join(" | ");u=`| |${u}|`;let d=Array(a+2).fill("---").join(" |");d=`|${d}|`,l=`${u}\n${d}\n`;for(let n=0;n<s+1;n++){const i=[];for(let s=0;s<a+1;s++){const a=(null===(o=null===(t=null==e?void 0:e[n])||void 0===t?void 0:t[s])||void 0===o?void 0:o.v)||null;a&&"string"==typeof a?i.push(a):a&&"object"==typeof a?"image"===(null==a?void 0:a.class)&&(null==a?void 0:a.src)?i.push(`![${null==a?void 0:a.name}'](${null==a?void 0:a.src})`):"checkbox"===(null==a?void 0:a.class)?i.push((null==a?void 0:a.value)?"[x] ":"[ ] "):"link"===(null==a?void 0:a.class)?i.push(`[${null==a?void 0:a.text}](${null==a?void 0:a.url})`):"select"===(null==a?void 0:a.class)&&i.push(null===(r=null==a?void 0:a.value)||void 0===r?void 0:r.join(",")):i.push(null)}l=`${l}${`| ${n+1} | ${i.join(" | ")}|`}\n`}return l}(e.data);r=`${r}\n${t}\n${o}`})),r};function A(e,t=[]){return function(e,t){try{const{host:o,pathname:r}=new URL(e);return!t.includes(o)&&Boolean(r)}catch(e){return!1}}(e,t)?`https://www.yuque.com/api/filetransfer/images?url=${encodeURIComponent(e)}&sign=${function(e){const t=p.createHash("sha256");return t.update(`${L}${e}`),t.digest("hex")}(e)}`:e}const M=y(g.finished);function B(e){return w(this,void 0,void 0,(function*(){const{fileUrl:t,savePath:o,token:r,key:n,fileName:i}=e;return c.get(t,Object.assign(Object.assign({},j({token:r,key:n})),{responseType:"stream"})).then((e=>w(this,void 0,void 0,(function*(){var r,n,s;if(null===(n=null===(r=e.request)||void 0===r?void 0:r.path)||void 0===n?void 0:n.startsWith("/login"))throw new Error(`"${i}" need token`);if(200===e.status){const r=m(o);return null===(s=e.data)||void 0===s||s.pipe(r),M(r).then((()=>({fileUrl:t,savePath:o})))}throw new Error(`response status ${e.status}`)}))))}))}const J=/\[(.*?)\]\((.*?)\)/g,q=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;function H(e){return w(this,void 0,void 0,(function*(){const{mdData:t,savePath:o,attachmentsDir:n,articleTitle:i,token:s,key:c}=e,d=(t.match(J)||[]).filter((e=>q.test(e)));if(0===d.length)return{mdData:t};const h=u({text:`下载 "${i}" 的附件中...`,stream:l});"test"!==a.NODE_ENV&&h.start();const f=r.resolve(o,n),p=d.map((e=>function(e,t){const[,o,n]=q.exec(e)||[];if(!n)return!1;const i=o||n.split("/").at(-1);if(!i)return!1;const s=r.join(t,i);return{fileName:i,url:n,rawMd:e,currentFilePath:s}}(e,f))).filter((e=>!1!==e));v(f,{recursive:!0});const m=p.map((e=>B({fileUrl:e.url,savePath:e.currentFilePath,token:s,key:c,fileName:e.fileName}))),g=yield Promise.all(m).finally((function(){h&&h.stop()}));let y=t;return g.forEach((e=>{const t=p.find((t=>t.url===e.fileUrl));if(t){const e=`[附件: ${t.fileName}](${n}/${t.fileName})`;y=y.replace(t.rawMd,e)}})),{mdData:y}}))}function K(e){const t=[];return V(e,(function(e,o){"link"===e.type&&t.push({node:e,keyChain:o})})),t}function V(e,t,o=[]){t(e,o),Array.isArray(e.children)&&(o.push("children"),e.children.forEach(((e,r)=>{V(e,t,[...o,String(r)])})))}const W=/name="audio" value="data:(.*?audioId.*?)".*?><\/card>/gm;function G(e){return w(this,void 0,void 0,(function*(){const{mdData:t,htmlData:o,savePath:n,attachmentsDir:i,articleTitle:s,token:c,key:d}=e,h=function(e){return k(e)}(t),f=K(h).filter((e=>/_lake_card.*?videoId/.test(e.node.url))),p=function(e){const t=e.match(W)||[];try{return t.map((e=>e.replace(W,"$1"))).map((e=>JSON.parse(decodeURIComponent(e))))}catch(e){return[]}}(o);if(0===f.length&&0===p.length)return{mdData:t};const m=u({text:`下载 "${s}" 的音视频中...`,stream:l});"test"!==a.NODE_ENV&&m.start();const g=r.resolve(n,i);v(g,{recursive:!0});let y=t;try{if(f.length>0){const t=yield function(e,t,o){return w(this,void 0,void 0,(function*(){const{key:n,token:i}=t,s=e.map((e=>w(this,void 0,void 0,(function*(){var t,s;const a=function(e){var t;try{const o=null!==(t=new URL(e).searchParams.get("_lake_card"))&&void 0!==t?t:"",r=decodeURIComponent(o),n=JSON.parse(r);return{name:(null==n?void 0:n.name)||"",videoId:(null==n?void 0:n.videoId)||""}}catch(e){return!1}}(e.node.url);if(!a)return!1;const l=yield Q({videoId:a.videoId,key:n,token:i});if(!l)return!1;const c=null!==(s=null!==(t=a.name)&&void 0!==t?t:a.videoId.split("/").at(-1))&&void 0!==s?s:a.videoId;return{videoInfo:Object.assign(Object.assign({},a),l),astNode:e,fileName:c,currentFilePath:r.join(o,c)}}))));return(yield Promise.all(s)).filter(Y)}))}(f,e,g),o=t.map((e=>B({fileUrl:e.videoInfo.video,savePath:e.currentFilePath,token:c,key:d,fileName:e.videoInfo.name})));(yield Promise.all(o)).forEach((e=>{const o=t.find((t=>t.videoInfo.video===e.fileUrl));o&&(o.astNode.node.url=`${i}${r.sep}${o.fileName}`,o.astNode.node.children=[{type:"text",value:`音视频附件: ${o.videoInfo.name}`}])})),y=function(e){return $(e)}(h)}if(p.length>0){const t=yield function(e,t,o){return w(this,void 0,void 0,(function*(){const{key:n,token:i}=t,s=e.map((e=>w(this,void 0,void 0,(function*(){var t;const s=yield Q({videoId:e.audioId,key:n,token:i});if(!s)return!1;const a=null!==(t=null==e?void 0:e.fileName)&&void 0!==t?t:e.id;return{audioInfo:Object.assign(Object.assign({},e),s),fileName:a,currentFilePath:r.join(o,a)}}))));return(yield Promise.all(s)).filter(Y)}))}(p,e,g),o=t.map((e=>B({fileUrl:e.audioInfo.audio,savePath:e.currentFilePath,token:c,key:d,fileName:e.audioInfo.fileName}))),n=yield Promise.all(o);let s="\n\n> [yuque-dl warn]: 由于语雀markdown接口限制, 无法准确定位音频文件在文档中所在位置, 所以统一所有音频放到一起\n";n.forEach((e=>{const o=t.find((t=>t.audioInfo.audio===e.fileUrl));o&&(s+=`> - [音视频附件: ${o.audioInfo.fileName}](${i}${r.sep}${o.fileName})\n`)})),y+=s}}finally{m&&m.stop()}return{mdData:y}}))}function Q(e){let t="https://www.yuque.com/api/video";const{videoId:o,token:r,key:n}=e,i=new URLSearchParams;return i.set("video_id",o),t=`${t}?${i.toString()}`,c.get(t,j({token:r,key:n})).then((({data:e,status:t})=>{const o=e.data;return 200===t&&"success"===o.status&&o.info})).catch((()=>!1))}function Y(e){return!!e}function z(e){return w(this,void 0,void 0,(function*(){var o,r,n,i,s,c,h,f,p,m;const{articleInfo:v,progressBar:g,options:y}=e,{token:k,key:$}=y,{bookId:w,itemUrl:b,savePath:N,saveFilePath:P,uuid:L,articleUrl:D,articleTitle:S,ignoreImg:T,host:U,imageServiceDomains:x}=v,C={articleUrl:b,bookId:w,token:k,host:U,key:$},{httpStatus:j,apiUrl:M,response:B}=yield R(C),J=null===(r=null===(o=null==B?void 0:B.data)||void 0===o?void 0:o.type)||void 0===r?void 0:r.toLocaleLowerCase();let q="";if(J===I.SHEET){const{response:e}=yield R(C,!1);try{const t=null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.content,o=t?JSON.parse(t):{},r=null==o?void 0:o.sheet;q=r?F(r):""}catch(e){const t=E.get(J);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([I.BOARD,I.TABLE].includes(J)){const e=E.get(J);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof(null===(i=null==B?void 0:B.data)||void 0===i?void 0:i.sourcecode))throw new Error(`download article Error: ${M}, http status ${j}`);q=B.data.sourcecode,q=function(e){const t=/!\[(.*?)\]\((http.*?latex.*?)\)/gm,o=e.match(t);let r=e;const n=e;try{null==o||o.forEach((e=>{var o,n;t.lastIndex=0;const i=null!==(n=null===(o=t.exec(e))||void 0===o?void 0:o[2])&&void 0!==n?n:"",{pathname:s,search:a}=new URL(i);if(!s.endsWith(".svg")&&a){const t=decodeURIComponent(a);r=r.replace(e,t.slice(1))}}))}catch(e){return n}return r}(q)}const K=function(e){if(!e)return[];const t=/!\[(.*?)\]\((.*?)\)/gm;let o=Array.from(e.match(t)||[]);return o=o.map((e=>(e=e.replace(t,"$2"),/^http.*/g.test(e)?e:""))).filter((e=>Boolean(e))),o}(q),V=null!==(h=null===(c=null===(s=(yield R(C,!1)).response)||void 0===s?void 0:s.data)||void 0===c?void 0:c.content)&&void 0!==h?h:"";K.length&&!T&&(q=function(e,t,o){if(!o)return t;const r=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let i,s=!0;for(;s||Boolean(i);)if(s=!1,i=r.exec(o),null==i?void 0:i[1])try{const e=decodeURIComponent(i[1]),t=JSON.parse(e);n.push((null==t?void 0:t.src)||"")}catch(e){n.push("")}const a=new Map;return e.forEach((e=>{const{origin:o,pathname:r}=new URL(e),i=`${o}${r}`,s=n.find(((e,t)=>{const o=new RegExp(`${i}.*?`).test(e);return o&&n.splice(t,1),o}));if(s){const o=new RegExp(e,"g"),r=a.get(e)||0;let n=0;t=t.replace(o,(e=>{let t=e;return n===r&&(t=s),n+=1,t})),a.set(e,r+1)}})),t}(K,q,V));const W={toc:y.toc,articleTitle:S,articleUrl:D,articleUpdateTime:O(null!==(p=null===(f=null==B?void 0:B.data)||void 0===f?void 0:f.content_updated_at)&&void 0!==p?p:"")},Q=[];try{g.pause(),console.log("");q=(yield H({mdData:q,savePath:N,attachmentsDir:`./attachments/${_(L)}`,articleTitle:S,token:k,key:$})).mdData}catch(e){Q.push(`附件下载失败: ${e.message||"unknown error"}`)}finally{g.continue()}try{g.pause(),console.log("");q=(yield G({mdData:q,htmlData:V,savePath:N,attachmentsDir:`./attachments/${_(L)}`,articleTitle:S,token:k,key:$})).mdData}catch(e){Q.push(`音视频下载失败: ${e.message||"unknown error"}`)}finally{g.continue()}if(K.length&&!T){let e;g.pause(),console.log(""),"test"!==a.NODE_ENV&&(e=u({text:`下载 "${S}" 的图片中...`,stream:l}),e.start());let o=[],r=q;try{const e=yield d.run(q,{dist:N,imgDir:`./img/${L}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:D||"",transform:e=>A(e=e.replace("x-oss-process=image%2Fwatermark%2C",""),x)});o=e.errorInfo,r=e.data}catch(e){o=[e]}q=r;const n=()=>{e&&e.stop(),g.continue()};if(o.length>0){const e=o[0];let r="图片下载失败(失败的以远程链接保存): ";throw r=e.url?`${r}${null===(m=e.error)||void 0===m?void 0:m.message} ${e.url.slice(0,20)}...`:`${r}${e.message}`,yield t(P,X(q,W)),n(),new Error(`${r}`)}n()}try{if(yield t(P,X(q,W)),Q.length>0)throw new Error(Q[0]);return!0}catch(e){throw new Error(`${e.message}`)}}))}function X(e,t){const{articleTitle:o,articleUrl:r,toc:n}=t;let i=e;i=i.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((e,t,o)=>`| <br />- [${t}]${o}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),i=i.replace(/(\|?)(.*?)\|/gm,((e,t,o)=>`${t}${o.replace(/<br(\s?)\/>/gm,"")}|`)),i=i.replace(/<br(\s?)\/>/gm,"\n"),i=i.replace(/<a.*?>(\s*?)<\/a>/gm,"");const s=o?`# ${o}\n\n`:"";let a=n?h(i).content:"";a&&(a=`${a}\n\n---\n\n`);let l="\n\n";return t.articleUpdateTime&&(l+=`> 更新: ${t.articleUpdateTime} \n`),r&&(l+=`> 原文: <${r}>`),i=`${s}${a}${i}${l}`,i}function Z(e,t){return w(this,void 0,void 0,(function*(){if(!function(e){if("function"==typeof URL.canParse)return URL.canParse(e);try{return new URL(e),!0}catch(e){return!1}}(e))throw new Error("Please enter a valid URL");const{bookId:n,tocList:i,bookName:s,bookDesc:a,bookSlug:l,host:u,imageServiceDomains:d}=yield((e,t)=>{const o=/decodeURIComponent\("(.+)"\)\);/m;return c.get(e,j(t)).then((({data:e="",status:t})=>200===t?e:"")).then((e=>{var t,r;const n=null!==(t=o.exec(e))&&void 0!==t?t:"";if(!n[1])return{};const i=JSON.parse(decodeURIComponent(n[1]));return i.book?{bookId:i.book.id,bookSlug:i.book.slug,tocList:i.book.toc||[],bookName:i.book.name||"",bookDesc:i.book.description||"",host:(null===(r=i.space)||void 0===r?void 0:r.host)||P,imageServiceDomains:i.imageServiceDomains||[]}:{}})).catch((e=>{var t;const o=null!==(t=null==e?void 0:e.message)&&void 0!==t?t:"";if(!o)throw new Error("unknown error");if(["getaddrinfo ENOTFOUND","read ECONNRESET","Client network socket disconnected before secure TLS connection was established"].some((e=>o.startsWith(e))))throw new Error("请检查网络(是否正常联网/是否开启了代理软件)");throw new Error(o)}))})(e,{token:t.token,key:t.key});if(!n)throw new Error("No found book id");if(!i||0===i.length)throw new Error("No found toc list");const h=r.resolve(t.distDir,s?_(s):String(n));yield o(h,{recursive:!0});const f=i.length,p=new S(h,f);if(yield p.init(),p.curr===f)return p.bar&&p.bar.stop(),void D.info(`√ 已完成: ${h}`);const m=new Map;p.isDownloadInterrupted&&p.progressInfo.forEach((e=>{m.set(e.toc.uuid,e)}));const v=e.replace(new RegExp(`(.*?/${l}).*`),"$1");yield function(e){return w(this,void 0,void 0,(function*(){const{articleUrlPrefix:t,total:n,uuidMap:i,tocList:s,bookPath:a,bookId:l,progressBar:c,host:u,options:d,imageServiceDomains:h=[]}=e;let f=0,p=0,m=0;const v=[],g=[];for(let e=0;e<n;e++){const t=s[e];if("string"!=typeof t.type)continue;if(i.get(t.uuid))continue;const r=t.type.toLocaleLowerCase();if(r===b.TITLE||""!==t.child_uuid||r===b.LINK){let e=t;const n=[],s=[];for(;e;)n.unshift(_(e.title)),s.unshift(e.uuid),e=i.get(e.parent_uuid)?i.get(e.parent_uuid).toc:void 0;const l={path:n.map(_).join("/"),pathTitleList:n,pathIdList:s,toc:t};r===b.LINK?(m+=1,g.push(l)):yield o(`${a}/${n.map(_).join("/")}`,{recursive:!0}),i.set(t.uuid,l),r===I.DOC?yield y(t):yield c.updateProgress(l,r!==b.LINK)}else t.url&&(yield y(t))}function y(e){return w(this,void 0,void 0,(function*(){p+=1;let o={path:"",pathTitleList:[],pathIdList:[]};const n=e.type.toLocaleLowerCase();i.get(e.parent_uuid)&&(o=i.get(e.parent_uuid));const s=_(e.title),m=[...o.pathTitleList,s],g=[...o.pathIdList,e.uuid];let y=[...o.pathTitleList,`${s}.md`].map(_).join("/"),k=o.pathTitleList.map(_).join("/");n===I.DOC&&e.child_uuid&&(y=[...o.pathTitleList,s,"index.md"].map(_).join("/"),k=m.map(_).join("/"));const $={path:y,savePath:k,pathTitleList:m,pathIdList:g,toc:e};let w=!0;const b=`${t}/${e.url}`;try{const t={bookId:l,itemUrl:e.url,savePath:r.resolve(a,$.savePath),saveFilePath:r.resolve(a,$.path),uuid:e.uuid,articleUrl:b,articleTitle:e.title,ignoreImg:d.ignoreImg,host:u,imageServiceDomains:h};yield z({articleInfo:t,progressBar:c,options:d})}catch(e){w=!1,f+=1,v.push({articleUrl:b,errItem:$,errMsg:e.message,err:e})}i.set(e.uuid,$),yield c.updateProgress($,w)}))}if(m>0){D.warn("该知识库存在以下外链文章");for(const e of g)D.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(f>0){D.error(`本次执行总数${p}篇,✕ 失败${f}篇`);for(const e of v)D.error(`《${e.errItem.path}》: ${e.articleUrl}`),e.errMsg.split("\n").forEach((e=>{D.error(`———— ✕ ${e}`)}));D.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}))}({articleUrlPrefix:v,total:f,uuidMap:m,tocList:i,bookPath:h,bookId:n,progressBar:p,host:u,options:t,imageServiceDomains:d});const g=new x({bookPath:h,bookName:s,bookDesc:a,uuidMap:m});yield g.genFile(),D.info(`√ 生成目录 ${r.resolve(h,"index.md")}`),p.curr===f&&D.info(`√ 已完成: ${h}`)}))}export{w as _,D as l,Z as m};
package/dist/es/index.js CHANGED
@@ -1 +1 @@
1
- import"node:fs/promises";import"node:path";export{m as main}from"./index-CIP6WwpQ.js";import"rand-user-agent";import"log4js";import"cli-progress";import"node:process";import"axios";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";import"node:fs";import"node:stream";import"node:util";import"mdast-util-from-markdown";import"mdast-util-to-markdown";
1
+ export{m as main}from"./index-DT4ximDd.js";import"node:fs/promises";import"node:path";import"rand-user-agent";import"log4js";import"cli-progress";import"node:process";import"axios";import"ora";import"pull-md-img";import"markdown-toc";import"pako";import"node:crypto";import"node:fs";import"node:stream";import"node:util";import"mdast-util-from-markdown";import"mdast-util-to-markdown";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yuque-dl",
3
- "version": "1.0.68",
3
+ "version": "1.0.69",
4
4
  "description": "yuque 知识库下载",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "ES2020",
3
+ "target": "ES2015",
4
4
  "module": "ESNext",
5
5
  "moduleResolution": "bundler",
6
6
  "strict": true,
package/dist/cjs/cli.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var e=require("node:fs"),n=require("cac"),r=require("semver"),t=require("./index-3vpToKvl.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("node:process"),require("axios"),require("ora"),require("pull-md-img"),require("markdown-toc"),require("pako"),require("node:crypto"),require("node:stream"),require("node:util"),require("mdast-util-from-markdown"),require("mdast-util-to-markdown");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 +0,0 @@
1
- "use strict";var e=require("node:fs/promises"),t=require("node:path"),r=require("rand-user-agent"),n=require("log4js"),o=require("cli-progress"),a=require("node:process"),i=require("axios"),s=require("ora"),c=require("pull-md-img"),l=require("markdown-toc"),u=require("pako"),d=require("node:crypto"),h=require("node:fs"),p=require("node:stream"),f=require("node:util"),m=require("mdast-util-from-markdown"),g=require("mdast-util-to-markdown");function w(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var k,y,$=w(p);!function(e){e.TITLE="title",e.LINK="link",e.DOC="doc"}(k||(k={})),function(e){e.BOARD="board",e.TABLE="table",e.SHEET="sheet",e.DOC="doc"}(y||(y={}));const v=new Map([[y.BOARD,"画板类型"],[y.TABLE,"数据表类型"],[y.SHEET,"表格类型"],[y.DOC,"文档类型"]]),I="_yuque_session",b="https://www.yuque.com",E="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",N=(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 P{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,N.info("根据上次数据继续断点下载")),this.bar=new o.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},o.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 L({browser:e="chrome",os:t="mac os",device:n="desktop"}){n=n.toLowerCase(),e=e.toLowerCase(),t=t.toLowerCase();let o=r(n,e,t);if("chrome"===e)for(;o.includes("Chrome-Lighthouse")||o.includes("Gener8")||o.includes("HeadlessChrome")||o.includes("SMTBot");)o=r(n,e,t);if("safari"===e)for(;o.includes("Applebot");)o=r(n,e,t);return o}function D(e){return e.toString().padStart(2,"0")}function S(e){const t=new Date(e);if(isNaN(t.getTime()))return"";const r=t.getFullYear(),n=t.getMonth()+1,o=t.getDate(),a=t.getHours(),i=t.getMinutes(),s=t.getSeconds();return`${r}-${D(n)}-${D(o)} ${D(a)}:${D(i)}:${D(s)}`}class T{constructor(e){this.summaryInfo=e}async genFile(){const{bookName:t,bookDesc:r,bookPath:n,uuidMap:o}=this.summaryInfo;let a=`# ${t}\n\n`;r&&(a+=`> ${r}\n\n`);let i=a;const s=[];o.forEach((e=>{const t=e.toc,r=t.parent_uuid,n=this.findTree(s,r),o={text:t.title.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/,""),id:t.uuid,level:1,type:"link"},a=t.type.toLocaleLowerCase();a===k.TITLE||""!==t.child_uuid?(o.type="title","boolean"!=typeof n?(Array.isArray(n.children)||(n.children=[]),o.level=n.level+1,n.children.push(o)):(o.level=1,s.push(o)),a===k.DOC&&(o.link=e.path)):(o.type="link",o.link=a===k.LINK?e.toc.url:e.path,"boolean"!=typeof n?(Array.isArray(n.children)||(n.children=[]),o.level=n.level+1,n.children.push(o)):(o.level=1,s.push(o)))}));i+=this.genSummaryContent(s,"");try{await e.writeFile(`${n}/index.md`,i)}catch(e){N.error("Generate Summary Error")}return i}genSummaryContent(e,t){for(const r of e){if(r.type===k.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===k.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 U(e){const{key:t=I,token:r}=e,n={"user-agent":L({browser:"chrome",device:"desktop"})};return r&&(n.cookie=`${t}=${r};`),n}function O(e){const t={headers:U(e),beforeRedirect:t=>{t.headers={...t?.headers||{},...U(e)}}};return"test"===a.env.NODE_ENV&&(t.proxy=!1),t}const x=(e,t=!0)=>{const{articleUrl:r,bookId:n,token:o,key:a,host:s=b}=e;let c=`${s}/api/docs/${r}`;const l={book_id:String(n),merge_dynamic_data:String(!1)};t&&(l.mode="markdown");const u=new URLSearchParams(l).toString();return c=`${c}?${u}`,i.get(c,O({token:o,key:a})).then((({data:e,status:t})=>({apiUrl:c,httpStatus:t,response:e})))};function C(e){if(!e)return"";return e.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const R=e=>{if(!e)return"";const t=u.inflate(e,{to:"string"}),r=JSON.parse(t);let n="";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 n=e[t];n&&(r=r.concat(Object.keys(n)))}));const n=Math.max(...t.map((e=>Number(e)))),o=Math.max(...r.map((e=>Number(e))));if(n<0||o<0)return"";let a="";const i="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let s=Array(o+1).fill(" ").map(((e,t)=>{const r=t%i.length;return i[r]})).join(" | ");s=`| |${s}|`;let c=Array(o+2).fill("---").join(" |");c=`|${c}|`,a=`${s}\n${c}\n`;for(let t=0;t<n+1;t++){const r=[];for(let n=0;n<o+1;n++){const o=e?.[t]?.[n]?.v||null;o&&"string"==typeof o?r.push(o):o&&"object"==typeof o?"image"===o?.class&&o?.src?r.push(`![${o?.name}'](${o?.src})`):"checkbox"===o?.class?r.push(o?.value?"[x] ":"[ ] "):"link"===o?.class?r.push(`[${o?.text}](${o?.url})`):"select"===o?.class&&r.push(o?.value?.join(",")):r.push(null)}a=`${a}${`| ${t+1} | ${r.join(" | ")}|`}\n`}return a}(e.data);n=`${n}\n${t}\n${r}`})),n};function q(e,t=[]){return function(e,t){try{const{host:r,pathname:n}=new URL(e);return!t.includes(r)&&Boolean(n)}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(`${E}${e}`),t.digest("hex")}(e)}`:e}const F=f.promisify($.finished);async function _(e){const{fileUrl:t,savePath:r,token:n,key:o,fileName:a}=e;return i.get(t,{...O({token:n,key:o}),responseType:"stream"}).then((async e=>{if(e.request?.path?.startsWith("/login"))throw new Error(`"${a}" need token`);if(200===e.status){const n=h.createWriteStream(r);return e.data?.pipe(n),F(n).then((()=>({fileUrl:t,savePath:r})))}throw new Error(`response status ${e.status}`)}))}const j=/\[(.*?)\]\((.*?)\)/g,A=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;async function M(e){const{mdData:r,savePath:n,attachmentsDir:o,articleTitle:i,token:c,key:l}=e,u=(r.match(j)||[]).filter((e=>A.test(e)));if(0===u.length)return{mdData:r};const d=s({text:`下载 "${i}" 的附件中...`,stream:a.stdout});"test"!==a.env.NODE_ENV&&d.start();const p=t.resolve(n,o),f=u.map((e=>function(e,r){const[,n,o]=A.exec(e)||[];if(!o)return!1;const a=n||o.split("/").at(-1);if(!a)return!1;const i=t.join(r,a);return{fileName:a,url:o,rawMd:e,currentFilePath:i}}(e,p))).filter((e=>!1!==e));h.mkdirSync(p,{recursive:!0});const m=f.map((e=>_({fileUrl:e.url,savePath:e.currentFilePath,token:c,key:l,fileName:e.fileName}))),g=await Promise.all(m).finally((function(){d&&d.stop()}));let w=r;return g.forEach((e=>{const t=f.find((t=>t.url===e.fileUrl));if(t){const e=`[附件: ${t.fileName}](${o}/${t.fileName})`;w=w.replace(t.rawMd,e)}})),{mdData:w}}function B(e){const t=[];return J(e,(function(e,r){"link"===e.type&&t.push({node:e,keyChain:r})})),t}function J(e,t,r=[]){t(e,r),Array.isArray(e.children)&&(r.push("children"),e.children.forEach(((e,n)=>{J(e,t,[...r,String(n)])})))}const H=/name="audio" value="data:(.*?audioId.*?)".*?><\/card>/gm;async function K(e){const{mdData:r,htmlData:n,savePath:o,attachmentsDir:i,articleTitle:c,token:l,key:u}=e,d=function(e){return m.fromMarkdown(e)}(r),p=B(d).filter((e=>/_lake_card.*?videoId/.test(e.node.url))),f=function(e){const t=e.match(H)||[];try{return t.map((e=>e.replace(H,"$1"))).map((e=>JSON.parse(decodeURIComponent(e))))}catch(e){return[]}}(n);if(0===p.length&&0===f.length)return{mdData:r};const w=s({text:`下载 "${c}" 的音视频中...`,stream:a.stdout});"test"!==a.env.NODE_ENV&&w.start();const k=t.resolve(o,i);h.mkdirSync(k,{recursive:!0});let y=r;try{if(p.length>0){const r=await async function(e,r,n){const{key:o,token:a}=r,i=e.map((async e=>{const r=function(e){try{const t=new URL(e).searchParams.get("_lake_card")??"",r=decodeURIComponent(t),n=JSON.parse(r);return{name:n?.name||"",videoId:n?.videoId||""}}catch(e){return!1}}(e.node.url);if(!r)return!1;const i=await W({videoId:r.videoId,key:o,token:a});if(!i)return!1;const s=r.name??r.videoId.split("/").at(-1)??r.videoId;return{videoInfo:{...r,...i},astNode:e,fileName:s,currentFilePath:t.join(n,s)}})),s=await Promise.all(i);return s.filter(V)}(p,e,k),n=r.map((e=>_({fileUrl:e.videoInfo.video,savePath:e.currentFilePath,token:l,key:u,fileName:e.videoInfo.name})));(await Promise.all(n)).forEach((e=>{const n=r.find((t=>t.videoInfo.video===e.fileUrl));n&&(n.astNode.node.url=`${i}${t.sep}${n.fileName}`,n.astNode.node.children=[{type:"text",value:`音视频附件: ${n.videoInfo.name}`}])})),y=function(e){return g.toMarkdown(e)}(d)}if(f.length>0){const r=await async function(e,r,n){const{key:o,token:a}=r,i=e.map((async e=>{const r=await W({videoId:e.audioId,key:o,token:a});if(!r)return!1;const i=e?.fileName??e.id;return{audioInfo:{...e,...r},fileName:i,currentFilePath:t.join(n,i)}})),s=await Promise.all(i);return s.filter(V)}(f,e,k),n=r.map((e=>_({fileUrl:e.audioInfo.audio,savePath:e.currentFilePath,token:l,key:u,fileName:e.audioInfo.fileName}))),o=await Promise.all(n);let a="\n\n> [yuque-dl warn]: 由于语雀markdown接口限制, 无法准确定位音频文件在文档中所在位置, 所以统一所有音频放到一起\n";o.forEach((e=>{const n=r.find((t=>t.audioInfo.audio===e.fileUrl));n&&(a+=`> - [音视频附件: ${n.audioInfo.fileName}](${i}${t.sep}${n.fileName})\n`)})),y+=a}}finally{w&&w.stop()}return{mdData:y}}function W(e){let t="https://www.yuque.com/api/video";const{videoId:r,token:n,key:o}=e,a=new URLSearchParams;return a.set("video_id",r),t=`${t}?${a.toString()}`,i.get(t,O({token:n,key:o})).then((({data:e,status:t})=>{const r=e.data;return 200===t&&"success"===r.status&&r.info})).catch((()=>!1))}function V(e){return!!e}async function z(t){const{articleInfo:r,progressBar:n,options:o}=t,{token:i,key:l}=o,{bookId:u,itemUrl:d,savePath:h,saveFilePath:p,uuid:f,articleUrl:m,articleTitle:g,ignoreImg:w,host:k,imageServiceDomains:$}=r,I={articleUrl:d,bookId:u,token:i,host:k,key:l},{httpStatus:b,apiUrl:E,response:N}=await x(I),P=N?.data?.type?.toLocaleLowerCase();let L="";if(P===y.SHEET){const{response:e}=await x(I,!1);try{const t=e?.data?.content,r=t?JSON.parse(t):{},n=r?.sheet;L=n?R(n):""}catch(e){const t=v.get(P);throw new Error(`download article Error: “${t}”解析错误 ${e}`)}}else{if([y.BOARD,y.TABLE].includes(P)){const e=v.get(P);throw new Error(`download article Error: 暂不支持“${e}”的文档`)}if("string"!=typeof N?.data?.sourcecode)throw new Error(`download article Error: ${E}, http status ${b}`);L=N.data.sourcecode,L=function(e){const t=/!\[(.*?)\]\((http.*?latex.*?)\)/gm,r=e.match(t);let n=e;const o=e;try{r?.forEach((e=>{t.lastIndex=0;const r=t.exec(e)?.[2]??"",{pathname:o,search:a}=new URL(r);if(!o.endsWith(".svg")&&a){const t=decodeURIComponent(a);n=n.replace(e,t.slice(1))}}))}catch(e){return o}return n}(L)}const D=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}(L),T=await x(I,!1),U=T.response?.data?.content??"";D.length&&!w&&(L=function(e,t,r){if(!r)return t;const n=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,o=[];let a,i=!0;for(;i||Boolean(a);)if(i=!1,a=n.exec(r),a?.[1])try{const e=decodeURIComponent(a[1]),t=JSON.parse(e);o.push(t?.src||"")}catch(e){o.push("")}const s=new Map;return e.forEach((e=>{const{origin:r,pathname:n}=new URL(e),a=`${r}${n}`,i=o.find(((e,t)=>{const r=new RegExp(`${a}.*?`).test(e);return r&&o.splice(t,1),r}));if(i){const r=new RegExp(e,"g"),n=s.get(e)||0;let o=0;t=t.replace(r,(e=>{let t=e;return o===n&&(t=i),o+=1,t})),s.set(e,n+1)}})),t}(D,L,U));const O={toc:o.toc,articleTitle:g,articleUrl:m,articleUpdateTime:S(N?.data?.content_updated_at??"")},F=[];try{n.pause(),console.log("");L=(await M({mdData:L,savePath:h,attachmentsDir:`./attachments/${C(f)}`,articleTitle:g,token:i,key:l})).mdData}catch(e){F.push(`附件下载失败: ${e.message||"unknown error"}`)}finally{n.continue()}try{n.pause(),console.log("");L=(await K({mdData:L,htmlData:U,savePath:h,attachmentsDir:`./attachments/${C(f)}`,articleTitle:g,token:i,key:l})).mdData}catch(e){F.push(`音视频下载失败: ${e.message||"unknown error"}`)}finally{n.continue()}if(D.length&&!w){let t;n.pause(),console.log(""),"test"!==a.env.NODE_ENV&&(t=s({text:`下载 "${g}" 的图片中...`,stream:a.stdout}),t.start());let r=[],o=L;try{const e=await c.run(L,{dist:h,imgDir:`./img/${f}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:m||"",transform:e=>q(e=e.replace("x-oss-process=image%2Fwatermark%2C",""),$)});r=e.errorInfo,o=e.data}catch(e){r=[e]}L=o;const i=()=>{t&&t.stop(),n.continue()};if(r.length>0){const t=r[0];let n="图片下载失败(失败的以远程链接保存): ";throw n=t.url?`${n}${t.error?.message} ${t.url.slice(0,20)}...`:`${n}${t.message}`,await e.writeFile(p,G(L,O)),i(),new Error(`${n}`)}i()}try{if(await e.writeFile(p,G(L,O)),F.length>0)throw new Error(F[0]);return!0}catch(e){throw new Error(`${e.message}`)}}function G(e,t){const{articleTitle:r,articleUrl:n,toc:o}=t;let a=e;a=a.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((e,t,r)=>`| <br />- [${t}]${r}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),a=a.replace(/(\|?)(.*?)\|/gm,((e,t,r)=>`${t}${r.replace(/<br(\s?)\/>/gm,"")}|`)),a=a.replace(/<br(\s?)\/>/gm,"\n"),a=a.replace(/<a.*?>(\s*?)<\/a>/gm,"");const i=r?`# ${r}\n\n`:"";let s=o?l(a).content:"";s&&(s=`${s}\n\n---\n\n`);let c="\n\n";return t.articleUpdateTime&&(c+=`> 更新: ${t.articleUpdateTime} \n`),n&&(c+=`> 原文: <${n}>`),a=`${i}${s}${a}${c}`,a}exports.logger=N,exports.main=async function(r,n){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:o,tocList:a,bookName:s,bookDesc:c,bookSlug:l,host:u,imageServiceDomains:d}=await((e,t)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return i.get(e,O(t)).then((({data:e="",status:t})=>200===t?e:"")).then((e=>{const t=r.exec(e)??"";if(!t[1])return{};const n=JSON.parse(decodeURIComponent(t[1]));return n.book?{bookId:n.book.id,bookSlug:n.book.slug,tocList:n.book.toc||[],bookName:n.book.name||"",bookDesc:n.book.description||"",host:n.space?.host||b,imageServiceDomains:n.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:n.token,key:n.key});if(!o)throw new Error("No found book id");if(!a||0===a.length)throw new Error("No found toc list");const h=t.resolve(n.distDir,s?C(s):String(o));await e.mkdir(h,{recursive:!0});const p=a.length,f=new P(h,p);if(await f.init(),f.curr===p)return f.bar&&f.bar.stop(),void N.info(`√ 已完成: ${h}`);const m=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((e=>{m.set(e.toc.uuid,e)}));const g=r.replace(new RegExp(`(.*?/${l}).*`),"$1");await async function(r){const{articleUrlPrefix:n,total:o,uuidMap:a,tocList:i,bookPath:s,bookId:c,progressBar:l,host:u,options:d,imageServiceDomains:h=[]}=r;let p=0,f=0,m=0;const g=[],w=[];for(let t=0;t<o;t++){const r=i[t];if("string"!=typeof r.type)continue;if(a.get(r.uuid))continue;const n=r.type.toLocaleLowerCase();if(n===k.TITLE||""!==r.child_uuid||n===k.LINK){let t=r;const o=[],i=[];for(;t;)o.unshift(C(t.title)),i.unshift(t.uuid),t=a.get(t.parent_uuid)?a.get(t.parent_uuid).toc:void 0;const c={path:o.map(C).join("/"),pathTitleList:o,pathIdList:i,toc:r};n===k.LINK?(m+=1,w.push(c)):await e.mkdir(`${s}/${o.map(C).join("/")}`,{recursive:!0}),a.set(r.uuid,c),n===y.DOC?await $(r):await l.updateProgress(c,n!==k.LINK)}else r.url&&await $(r)}async function $(e){f+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const o=e.type.toLocaleLowerCase();a.get(e.parent_uuid)&&(r=a.get(e.parent_uuid));const i=C(e.title),m=[...r.pathTitleList,i],w=[...r.pathIdList,e.uuid];let k=[...r.pathTitleList,`${i}.md`].map(C).join("/"),$=r.pathTitleList.map(C).join("/");o===y.DOC&&e.child_uuid&&(k=[...r.pathTitleList,i,"index.md"].map(C).join("/"),$=m.map(C).join("/"));const v={path:k,savePath:$,pathTitleList:m,pathIdList:w,toc:e};let I=!0;const b=`${n}/${e.url}`;try{const r={bookId:c,itemUrl:e.url,savePath:t.resolve(s,v.savePath),saveFilePath:t.resolve(s,v.path),uuid:e.uuid,articleUrl:b,articleTitle:e.title,ignoreImg:d.ignoreImg,host:u,imageServiceDomains:h};await z({articleInfo:r,progressBar:l,options:d})}catch(e){I=!1,p+=1,g.push({articleUrl:b,errItem:v,errMsg:e.message,err:e})}a.set(e.uuid,v),await l.updateProgress(v,I)}if(m>0){N.warn("该知识库存在以下外链文章");for(const e of w)N.warn(`———— ✕ ${e.path} ${e.toc.url}`)}if(p>0){N.error(`本次执行总数${f}篇,✕ 失败${p}篇`);for(const e of g)N.error(`《${e.errItem.path}》: ${e.articleUrl}`),e.errMsg.split("\n").forEach((e=>{N.error(`———— ✕ ${e}`)}));N.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:g,total:p,uuidMap:m,tocList:a,bookPath:h,bookId:o,progressBar:f,host:u,options:n,imageServiceDomains:d});const w=new T({bookPath:h,bookName:s,bookDesc:c,uuidMap:m});await w.genFile(),N.info(`√ 生成目录 ${t.resolve(h,"index.md")}`),f.curr===p&&N.info(`√ 已完成: ${h}`)};
package/dist/cjs/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";require("node:fs/promises"),require("node:path");var e=require("./index-3vpToKvl.js");require("rand-user-agent"),require("log4js"),require("cli-progress"),require("node:process"),require("axios"),require("ora"),require("pull-md-img"),require("markdown-toc"),require("pako"),require("node:crypto"),require("node:fs"),require("node:stream"),require("node:util"),require("mdast-util-from-markdown"),require("mdast-util-to-markdown"),exports.main=e.main;
@@ -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 a from"log4js";import s from"cli-progress";import{env as i,stdout as c}from"node:process";import l from"axios";import u from"ora";import d from"pull-md-img";import h from"markdown-toc";import p from"pako";import f from"node:crypto";import{createWriteStream as m,mkdirSync as g}from"node:fs";import*as w from"node:stream";import{promisify as k}from"node:util";import{fromMarkdown as y}from"mdast-util-from-markdown";import{toMarkdown as $}from"mdast-util-to-markdown";var v,I;!function(t){t.TITLE="title",t.LINK="link",t.DOC="doc"}(v||(v={})),function(t){t.BOARD="board",t.TABLE="table",t.SHEET="sheet",t.DOC="doc"}(I||(I={}));const b=new Map([[I.BOARD,"画板类型"],[I.TABLE,"数据表类型"],[I.SHEET,"表格类型"],[I.DOC,"文档类型"]]),E="_yuque_session",N="https://www.yuque.com",L="UXO91eVnUveQn8suOJaYMvBcWs9KptS8N5HoP8ezSeU4vqApZpy1CkPaTpkpQEx2W2mlhxL8zwS8UePwBgksUM0CTtAODbTTTDFD",P=(a.configure({appenders:{cheese:{type:"console",layout:{type:"pattern",pattern:"%[%c [%p]:%] %m%n"}}},categories:{default:{appenders:["cheese"],level:"trace"}}}),a.getLogger("yuque-dl"));class D{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,P.info("根据上次数据继续断点下载")),this.bar=new s.SingleBar({format:"Download [{bar}] {percentage}% | {value}/{total}"},s.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 S({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}function T(t){return t.toString().padStart(2,"0")}function U(t){const e=new Date(t);if(isNaN(e.getTime()))return"";const r=e.getFullYear(),o=e.getMonth()+1,n=e.getDate(),a=e.getHours(),s=e.getMinutes(),i=e.getSeconds();return`${r}-${T(o)}-${T(n)} ${T(a)}:${T(s)}:${T(i)}`}class x{constructor(t){this.summaryInfo=t}async genFile(){const{bookName:e,bookDesc:r,bookPath:o,uuidMap:n}=this.summaryInfo;let a=`# ${e}\n\n`;r&&(a+=`> ${r}\n\n`);let s=a;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"},a=e.type.toLocaleLowerCase();a===v.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)),a===v.DOC&&(n.link=t.path)):(n.type="link",n.link=a===v.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)))}));s+=this.genSummaryContent(i,"");try{await t.writeFile(`${o}/index.md`,s)}catch(t){P.error("Generate Summary Error")}return s}genSummaryContent(t,e){for(const r of t){if(r.type===v.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===v.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 C(t){const{key:e=E,token:r}=t,o={"user-agent":S({browser:"chrome",device:"desktop"})};return r&&(o.cookie=`${e}=${r};`),o}function O(t){const e={headers:C(t),beforeRedirect:e=>{e.headers={...e?.headers||{},...C(t)}}};return"test"===i.NODE_ENV&&(e.proxy=!1),e}const R=(t,e=!0)=>{const{articleUrl:r,bookId:o,token:n,key:a,host:s=N}=t;let i=`${s}/api/docs/${r}`;const c={book_id:String(o),merge_dynamic_data:String(!1)};e&&(c.mode="markdown");const u=new URLSearchParams(c).toString();return i=`${i}?${u}`,l.get(i,O({token:n,key:a})).then((({data:t,status:e})=>({apiUrl:i,httpStatus:e,response:t})))};function _(t){if(!t)return"";return t.replace(/[\\/:*?"<>|\n\r]/g,"_").replace(/\s/g,"").replace(/[\ud800-\udbff][\udc00-\udfff]/g,"")}const F=t=>{if(!t)return"";const e=p.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 a="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";let i=Array(n+1).fill(" ").map(((t,e)=>{const r=e%s.length;return s[r]})).join(" | ");i=`| |${i}|`;let c=Array(n+2).fill("---").join(" |");c=`|${c}|`,a=`${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(`![${n?.name}'](${n?.src})`):"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)}a=`${a}${`| ${e+1} | ${r.join(" | ")}|`}\n`}return a}(t.data);o=`${o}\n${e}\n${r}`})),o};function A(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 j=k(w.finished);async function M(t){const{fileUrl:e,savePath:r,token:o,key:n,fileName:a}=t;return l.get(e,{...O({token:o,key:n}),responseType:"stream"}).then((async t=>{if(t.request?.path?.startsWith("/login"))throw new Error(`"${a}" need token`);if(200===t.status){const o=m(r);return t.data?.pipe(o),j(o).then((()=>({fileUrl:e,savePath:r})))}throw new Error(`response status ${t.status}`)}))}const B=/\[(.*?)\]\((.*?)\)/g,J=/\[(.*?)\]\((.*?\.yuque\.com\/attachments.*?)\)/;async function q(t){const{mdData:e,savePath:r,attachmentsDir:n,articleTitle:a,token:s,key:l}=t,d=(e.match(B)||[]).filter((t=>J.test(t)));if(0===d.length)return{mdData:e};const h=u({text:`下载 "${a}" 的附件中...`,stream:c});"test"!==i.NODE_ENV&&h.start();const p=o.resolve(r,n),f=d.map((t=>function(t,e){const[,r,n]=J.exec(t)||[];if(!n)return!1;const a=r||n.split("/").at(-1);if(!a)return!1;const s=o.join(e,a);return{fileName:a,url:n,rawMd:t,currentFilePath:s}}(t,p))).filter((t=>!1!==t));g(p,{recursive:!0});const m=f.map((t=>M({fileUrl:t.url,savePath:t.currentFilePath,token:s,key:l,fileName:t.fileName}))),w=await Promise.all(m).finally((function(){h&&h.stop()}));let k=e;return w.forEach((t=>{const e=f.find((e=>e.url===t.fileUrl));if(e){const t=`[附件: ${e.fileName}](${n}/${e.fileName})`;k=k.replace(e.rawMd,t)}})),{mdData:k}}function H(t){const e=[];return K(t,(function(t,r){"link"===t.type&&e.push({node:t,keyChain:r})})),e}function K(t,e,r=[]){e(t,r),Array.isArray(t.children)&&(r.push("children"),t.children.forEach(((t,o)=>{K(t,e,[...r,String(o)])})))}const V=/name="audio" value="data:(.*?audioId.*?)".*?><\/card>/gm;async function W(t){const{mdData:e,htmlData:r,savePath:n,attachmentsDir:a,articleTitle:s,token:l,key:d}=t,h=function(t){return y(t)}(e),p=H(h).filter((t=>/_lake_card.*?videoId/.test(t.node.url))),f=function(t){const e=t.match(V)||[];try{return e.map((t=>t.replace(V,"$1"))).map((t=>JSON.parse(decodeURIComponent(t))))}catch(t){return[]}}(r);if(0===p.length&&0===f.length)return{mdData:e};const m=u({text:`下载 "${s}" 的音视频中...`,stream:c});"test"!==i.NODE_ENV&&m.start();const w=o.resolve(n,a);g(w,{recursive:!0});let k=e;try{if(p.length>0){const e=await async function(t,e,r){const{key:n,token:a}=e,s=t.map((async t=>{const e=function(t){try{const e=new URL(t).searchParams.get("_lake_card")??"",r=decodeURIComponent(e),o=JSON.parse(r);return{name:o?.name||"",videoId:o?.videoId||""}}catch(t){return!1}}(t.node.url);if(!e)return!1;const s=await G({videoId:e.videoId,key:n,token:a});if(!s)return!1;const i=e.name??e.videoId.split("/").at(-1)??e.videoId;return{videoInfo:{...e,...s},astNode:t,fileName:i,currentFilePath:o.join(r,i)}})),i=await Promise.all(s);return i.filter(Q)}(p,t,w),r=e.map((t=>M({fileUrl:t.videoInfo.video,savePath:t.currentFilePath,token:l,key:d,fileName:t.videoInfo.name})));(await Promise.all(r)).forEach((t=>{const r=e.find((e=>e.videoInfo.video===t.fileUrl));r&&(r.astNode.node.url=`${a}${o.sep}${r.fileName}`,r.astNode.node.children=[{type:"text",value:`音视频附件: ${r.videoInfo.name}`}])})),k=function(t){return $(t)}(h)}if(f.length>0){const e=await async function(t,e,r){const{key:n,token:a}=e,s=t.map((async t=>{const e=await G({videoId:t.audioId,key:n,token:a});if(!e)return!1;const s=t?.fileName??t.id;return{audioInfo:{...t,...e},fileName:s,currentFilePath:o.join(r,s)}})),i=await Promise.all(s);return i.filter(Q)}(f,t,w),r=e.map((t=>M({fileUrl:t.audioInfo.audio,savePath:t.currentFilePath,token:l,key:d,fileName:t.audioInfo.fileName}))),n=await Promise.all(r);let s="\n\n> [yuque-dl warn]: 由于语雀markdown接口限制, 无法准确定位音频文件在文档中所在位置, 所以统一所有音频放到一起\n";n.forEach((t=>{const r=e.find((e=>e.audioInfo.audio===t.fileUrl));r&&(s+=`> - [音视频附件: ${r.audioInfo.fileName}](${a}${o.sep}${r.fileName})\n`)})),k+=s}}finally{m&&m.stop()}return{mdData:k}}function G(t){let e="https://www.yuque.com/api/video";const{videoId:r,token:o,key:n}=t,a=new URLSearchParams;return a.set("video_id",r),e=`${e}?${a.toString()}`,l.get(e,O({token:o,key:n})).then((({data:t,status:e})=>{const r=t.data;return 200===e&&"success"===r.status&&r.info})).catch((()=>!1))}function Q(t){return!!t}async function Y(t){const{articleInfo:r,progressBar:o,options:n}=t,{token:a,key:s}=n,{bookId:l,itemUrl:h,savePath:p,saveFilePath:f,uuid:m,articleUrl:g,articleTitle:w,ignoreImg:k,host:y,imageServiceDomains:$}=r,v={articleUrl:h,bookId:l,token:a,host:y,key:s},{httpStatus:E,apiUrl:N,response:L}=await R(v),P=L?.data?.type?.toLocaleLowerCase();let D="";if(P===I.SHEET){const{response:t}=await R(v,!1);try{const e=t?.data?.content,r=e?JSON.parse(e):{},o=r?.sheet;D=o?F(o):""}catch(t){const e=b.get(P);throw new Error(`download article Error: “${e}”解析错误 ${t}`)}}else{if([I.BOARD,I.TABLE].includes(P)){const t=b.get(P);throw new Error(`download article Error: 暂不支持“${t}”的文档`)}if("string"!=typeof L?.data?.sourcecode)throw new Error(`download article Error: ${N}, http status ${E}`);D=L.data.sourcecode,D=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:a}=new URL(r);if(!n.endsWith(".svg")&&a){const e=decodeURIComponent(a);o=o.replace(t,e.slice(1))}}))}catch(t){return n}return o}(D)}const S=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}(D),T=await R(v,!1),x=T.response?.data?.content??"";S.length&&!k&&(D=function(t,e,r){if(!r)return e;const o=/<card.*?name="image".*?value="data:(.*?)">(.*?)<\/card>/gm,n=[];let a,s=!0;for(;s||Boolean(a);)if(s=!1,a=o.exec(r),a?.[1])try{const t=decodeURIComponent(a[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),a=`${r}${o}`,s=n.find(((t,e)=>{const r=new RegExp(`${a}.*?`).test(t);return r&&n.splice(e,1),r}));if(s){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=s),n+=1,e})),i.set(t,o+1)}})),e}(S,D,x));const C={toc:n.toc,articleTitle:w,articleUrl:g,articleUpdateTime:U(L?.data?.content_updated_at??"")},O=[];try{o.pause(),console.log("");D=(await q({mdData:D,savePath:p,attachmentsDir:`./attachments/${_(m)}`,articleTitle:w,token:a,key:s})).mdData}catch(t){O.push(`附件下载失败: ${t.message||"unknown error"}`)}finally{o.continue()}try{o.pause(),console.log("");D=(await W({mdData:D,htmlData:x,savePath:p,attachmentsDir:`./attachments/${_(m)}`,articleTitle:w,token:a,key:s})).mdData}catch(t){O.push(`音视频下载失败: ${t.message||"unknown error"}`)}finally{o.continue()}if(S.length&&!k){let t;o.pause(),console.log(""),"test"!==i.NODE_ENV&&(t=u({text:`下载 "${w}" 的图片中...`,stream:c}),t.start());let r=[],n=D;try{const t=await d.run(D,{dist:p,imgDir:`./img/${m}`,isIgnoreConsole:!0,errorStillReturn:!0,referer:g||"",transform:t=>A(t=t.replace("x-oss-process=image%2Fwatermark%2C",""),$)});r=t.errorInfo,n=t.data}catch(t){r=[t]}D=n;const a=()=>{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,z(D,C)),a(),new Error(`${o}`)}a()}try{if(await e(f,z(D,C)),O.length>0)throw new Error(O[0]);return!0}catch(t){throw new Error(`${t.message}`)}}function z(t,e){const{articleTitle:r,articleUrl:o,toc:n}=e;let a=t;a=a.replace(/\|\s?<br \/>- \[(x|\s)\]([\s\S\n]*?)\|/gm,((t,e,r)=>`| <br />- [${e}]${r}|`.replace(/\n/gm,"").replace(/<br(\s?)\/>/gm,""))),a=a.replace(/(\|?)(.*?)\|/gm,((t,e,r)=>`${e}${r.replace(/<br(\s?)\/>/gm,"")}|`)),a=a.replace(/<br(\s?)\/>/gm,"\n"),a=a.replace(/<a.*?>(\s*?)<\/a>/gm,"");const s=r?`# ${r}\n\n`:"";let i=n?h(a).content:"";i&&(i=`${i}\n\n---\n\n`);let c="\n\n";return e.articleUpdateTime&&(c+=`> 更新: ${e.articleUpdateTime} \n`),o&&(c+=`> 原文: <${o}>`),a=`${s}${i}${a}${c}`,a}async function X(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:a,bookName:s,bookDesc:i,bookSlug:c,host:u,imageServiceDomains:d}=await((t,e)=>{const r=/decodeURIComponent\("(.+)"\)\);/m;return l.get(t,O(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||N,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(!a||0===a.length)throw new Error("No found toc list");const h=o.resolve(e.distDir,s?_(s):String(n));await r(h,{recursive:!0});const p=a.length,f=new D(h,p);if(await f.init(),f.curr===p)return f.bar&&f.bar.stop(),void P.info(`√ 已完成: ${h}`);const m=new Map;f.isDownloadInterrupted&&f.progressInfo.forEach((t=>{m.set(t.toc.uuid,t)}));const g=t.replace(new RegExp(`(.*?/${c}).*`),"$1");await async function(t){const{articleUrlPrefix:e,total:n,uuidMap:a,tocList:s,bookPath:i,bookId:c,progressBar:l,host:u,options:d,imageServiceDomains:h=[]}=t;let p=0,f=0,m=0;const g=[],w=[];for(let t=0;t<n;t++){const e=s[t];if("string"!=typeof e.type)continue;if(a.get(e.uuid))continue;const o=e.type.toLocaleLowerCase();if(o===v.TITLE||""!==e.child_uuid||o===v.LINK){let t=e;const n=[],s=[];for(;t;)n.unshift(_(t.title)),s.unshift(t.uuid),t=a.get(t.parent_uuid)?a.get(t.parent_uuid).toc:void 0;const c={path:n.map(_).join("/"),pathTitleList:n,pathIdList:s,toc:e};o===v.LINK?(m+=1,w.push(c)):await r(`${i}/${n.map(_).join("/")}`,{recursive:!0}),a.set(e.uuid,c),o===I.DOC?await k(e):await l.updateProgress(c,o!==v.LINK)}else e.url&&await k(e)}async function k(t){f+=1;let r={path:"",pathTitleList:[],pathIdList:[]};const n=t.type.toLocaleLowerCase();a.get(t.parent_uuid)&&(r=a.get(t.parent_uuid));const s=_(t.title),m=[...r.pathTitleList,s],w=[...r.pathIdList,t.uuid];let k=[...r.pathTitleList,`${s}.md`].map(_).join("/"),y=r.pathTitleList.map(_).join("/");n===I.DOC&&t.child_uuid&&(k=[...r.pathTitleList,s,"index.md"].map(_).join("/"),y=m.map(_).join("/"));const $={path:k,savePath:y,pathTitleList:m,pathIdList:w,toc:t};let v=!0;const b=`${e}/${t.url}`;try{const e={bookId:c,itemUrl:t.url,savePath:o.resolve(i,$.savePath),saveFilePath:o.resolve(i,$.path),uuid:t.uuid,articleUrl:b,articleTitle:t.title,ignoreImg:d.ignoreImg,host:u,imageServiceDomains:h};await Y({articleInfo:e,progressBar:l,options:d})}catch(t){v=!1,p+=1,g.push({articleUrl:b,errItem:$,errMsg:t.message,err:t})}a.set(t.uuid,$),await l.updateProgress($,v)}if(m>0){P.warn("该知识库存在以下外链文章");for(const t of w)P.warn(`———— ✕ ${t.path} ${t.toc.url}`)}if(p>0){P.error(`本次执行总数${f}篇,✕ 失败${p}篇`);for(const t of g)P.error(`《${t.errItem.path}》: ${t.articleUrl}`),t.errMsg.split("\n").forEach((t=>{P.error(`———— ✕ ${t}`)}));P.error("o(╥﹏╥)o 由于网络波动或链接失效以上下载失败,可重新执行命令重试(PS:不会影响已下载成功的数据)")}}({articleUrlPrefix:g,total:p,uuidMap:m,tocList:a,bookPath:h,bookId:n,progressBar:f,host:u,options:e,imageServiceDomains:d});const w=new x({bookPath:h,bookName:s,bookDesc:i,uuidMap:m});await w.genFile(),P.info(`√ 生成目录 ${o.resolve(h,"index.md")}`),f.curr===p&&P.info(`√ 已完成: ${h}`)}export{P as l,X as m};