@texonom/cli 1.4.7 → 1.5.1

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/build/src/main.js CHANGED
@@ -1,20 +1,563 @@
1
- import{Cli as ae,Builtins as re}from"clipanion";var H="Notion CLI",W="1.4.7";import{Option as $,Command as be}from"clipanion";import{NotionAPI as j}from"@texonom/nclient";import{getBlockTitle as E,getCanonicalPageId as U,parsePageId as G,formatDate as Y,getTextContent as O,getBlockParent as ie,defaultMapImageUrl as ne,getAllInSpace as se,getPageTitle as D,recursivePageTree as ce}from"@texonom/nutils";import{join as x}from"path";import{mkdir as q,readFile as N}from"fs/promises";import F from"JSONStream";import L from"graceful-fs";import{promisify as le}from"util";import X from"stream";import{format as de}from"prettier";import{isCollection as K,isSpace as ue}from"@texonom/ntypes";var Q=le(L.writeFile),A=(c,t,e="https://texonom.com")=>`${e}/${U(c,t)}`,J=class{constructor(t){this.promises=[];this.folder="texonom-raw";this.md="texonom-md";this.domain="https://texonom.com";this.validation=!0;this.update=!1;this.recursive=!1;this.prefetch=!1;this.load=!1;this.raw=!1;this.dataset=!1;this.debug=!1;this.wait=5;this.page=G(t.page),this.folder=t.folder??this.folder,this.domain=t.domain??this.domain,this.md=t.md??this.md,this.validation=t.validation??this.validation,this.update=t.update??this.update,this.recursive=t.recursive??this.recursive,this.prefetch=t.prefetch??this.prefetch,this.load=t.load??this.load,this.raw=t.raw??this.raw,this.dataset=t.dataset??this.dataset,this.token=t.token,this.notion=new j({authToken:this.token}),this.validation&&(Q=async()=>{})}async execute(){let t=G(this.page);if(this.load&&(console.time("Load raw data"),await this.loadRaw(),console.timeEnd("Load raw data")),this.prefetch&&(console.time("Fetch raw data"),await this.fetchRawSpace(t),console.timeEnd("Fetch raw data")),this.raw)console.time("Export raw files"),this.recursive?await this.saveRawSpace():await this.saveRawPage(t),console.timeEnd("Export raw files");else{console.time("Extract markdown"),await this.exportMd(t),console.timeEnd("Extract markdown");let e={id:this.page,title:E(this.recordMap.block[this.page].value,this.recordMap),blocks:1,pages:1,children:[],type:"page"};ce(this.recordMap,e),this.pageTree=e}await Promise.all(this.promises),this.update&&(this.recursive?await this.saveRawSpace():await this.saveRawPage(t))}async loadRaw(){let{recordMap:t,pageTree:e,pageMap:o}=await pe(this.folder);this.recordMap=t,this.pageTree=e,this.pageMap=o}async fetchRawSpace(t){let{recordMap:e,pageTree:o,pageMap:r}=await se(t,this.notion.getPage.bind(this.notion),this.notion.getBlocks.bind(this.notion),this.notion.fetchCollections.bind(this.notion),{startRecordMap:this.recordMap,collectionConcurrency:100,concurrency:100,fetchOption:{timeout:1e4},debug:this.debug});this.pageMap=r,this.recordMap=e,this.pageTree=o}async saveRawSpace(){if(this.validation)return;await q(this.folder,{recursive:!0});let t=[];await q(x(this.folder,"recordMap"),{recursive:!0});for(let e in this.recordMap)this.saveJson(x("recordMap",e),this.recordMap[e]);this.saveJson("pageMap",this.pageMap),this.saveJson("pageTree",this.pageTree),await Promise.all(t)}saveJson(t,e){if(this.validation)return;let o=L.createWriteStream(`${x(this.folder,t)}.json`),r=F.stringifyObject();r.pipe(o);for(let a in e)r.write([a,e[a]]);r.end()}async saveRawPage(t){if(this.validation)return;await q(this.folder,{recursive:!0});let e=await this.notion.getPage(t),o=`${U(t,e)}`,r=JSON.stringify(e),a="json";r=await de(r,{parser:"json"}),await this.writeFile(`${x(this.folder,o)}.${a}`,r)}async writeFile(t,e){if(this.folder)await Q(t,e);else return}async exportMd(t){await q(this.md,{recursive:!0});try{let e=this.pageMap&&this.pageMap[t];e||(console.warn(`Missing from pageMap ${t}`),e=await this.notion.getPage(t)),this.recursive||(this.recordMap=e);try{e||(e=await this.notion.getPage(t))}catch{return}if(!["page","collection_view_page"].includes(e.block[t].value.type))throw new Error("Not a page");let o=await this.pageToMarkdown(t,e);this.pageMap[t]||(this.pageMap[t]=e);let r=x(this.md,`${U(t,e)}`);this.promises.push(this.writeFile(`${r}.md`,o))}catch(e){console.error(t,e)}}async pageToMarkdown(t,e){let o=await this.pageToMarkdownObj(t,e),r=`---
2
- Title: ${o.title}
3
- `;r+=`Parent: ${o.parent}
4
- `;let a=Object.keys(o).filter(i=>!["title","parent","body"].includes(i));for(let i of a)r+=`${i}: ${o[i]}
5
- `;return r+=`---
6
- `,r+=o.body,r}async pageToMarkdownObj(t,e){var g,h;let o=e.block[t].value,r={},a=await this.decorationsToMarkdown((g=o.properties)!=null&&g.title?o.properties.title:[["Untitled"]],e);r.title=a;let i=ie(o,e),n;if(ue(i)?n=i.name:K(i)?n=O(i.name):i&&(n=E(i,e)),K(n)){let u=n!=null&&n.schema?Object.keys(n.schema):[];u.splice(u.indexOf("title"),1);for(let l of u){let T=n.schema[l].name,b=n.schema[l].type,m="";switch(b){case"text":m=(h=o==null?void 0:o.properties)!=null&&h[l]?await this.decorationsToMarkdown(o.properties[l],e):"";break;case"created_by":{let w=await this.getUser(o.created_by_id,e);m=w?w.name:"Unknown";break}case"last_edited_by":{let w=await this.getUser(o.last_edited_by_id,e);m=w?w.name:"Unknown";break}case"created_time":m=Y(o.created_time);break;case"last_edited_time":m=Y(o.last_edited_time);break;default:m=""}r[T]=m}}let d=await this.childrenToMd(o,e,"",o);return r.body=d,r}async childrenToMd(t,e,o,r){var n,d,g,h,u,l,T,b,m,w,y,M,P;let a="",i=1;for(let S of t.content?t.content:[]){let s=await this.getBlock(S,e,`${S} from ${E(r,e)}`);if(!s)continue;let v=(n=s==null?void 0:s.properties)==null?void 0:n.title;switch(s.type){case"header":a+=`${o}# ${await this.decorationsToMarkdown(v,e)}`;break;case"sub_header":a+=`${o}## ${await this.decorationsToMarkdown(v,e)}`;break;case"sub_sub_header":a+=`${o}### ${await this.decorationsToMarkdown(v,e)}`;break;case"text":a+=`${o}${await this.decorationsToMarkdown(v,e)}`;break;case"bulleted_list":a+=`${o}- ${await this.decorationsToMarkdown(v,e)}`;break;case"numbered_list":a+=`${o}${i++}. ${await this.decorationsToMarkdown(v,e)}`;break;case"to_do":a+=`${o}- [ ] ${await this.decorationsToMarkdown(v,e)}`;break;case"toggle":a+=`${o}<details><summary>${o}${o}${await this.decorationsToMarkdown(v,e)}</summary>
7
- `;break;case"quote":a+=await this.decorationsToMarkdown(v,e,`
8
- ${o.trim()}> `)+`
9
- `;break;case"code":a+=`${o}\`\`\`type${await this.decorationsToMarkdown(v,e)}\`\`\``;break;case"equation":a+=`${o}$$${await this.decorationsToMarkdown(v,e)}$$`;break;case"callout":{a+=await this.decorationsToMarkdown(v,e,`
10
- ${o.trim()}> `)+`
11
- `;break}case"bookmark":{let p=`
12
- ${o.trim()}> `;a+=`${p}[${O((d=s.properties)!=null&&d.title?s.properties.title:[["Untitled"]])}](${O(s.properties.link)})
13
- `;break}case"external_object_instance":try{let p=s.format.original_url,R=s.format.attributes?(h=(g=s.format.attributes.filter(B=>B.id==="title")[0])==null?void 0:g.values)==null?void 0:h[0]:p;if(!p)break;a+=`${o}${o}[${R}](${p})${o}`;break}catch(p){console.error(p,s.id);break}case"collection_view_page":case"collection_view":{let p=await this.getCollection(s,e,`${s.id} from ${D(e)}`);if(!p)continue;a+=`${o}### ${await this.decorationsToMarkdown(p.name,e)}`,a+=`${o}|Title|
14
- |:-:|`;let R=s.view_ids.map(f=>{var k;return e.collection_view[f]||this.debug&&console.warn(`Missing view ${f} from ${p.name}`),(k=e.collection_view[f])==null?void 0:k.value}).filter(Boolean),B=[];for(let f of R){let k=await this.getCollectionView(p.id,f.id,e,`${p.name} ${f.name}`);if(k)for(let _ of k.blockIds)B.push(_);else break}for(let f of B){let k=(u=e.block[f])==null?void 0:u.value;k||this.debug&&console.warn(`no ${f} in ${p.name[0]}`),a+=`${o}|[${E(k,e)}](${A(f,e)})|`}if(this.recursive&&B.length)for(let f of B)this.promises.push(this.exportMd(f));break}case"page":{a+=`${o}${o}[${E(s,e)}](${A(s.id,e)})${o}`,this.recursive&&this.promises.push(this.exportMd(s.id));break}case"alias":{let p=(b=e.block[(T=(l=s.format)==null?void 0:l.alias_pointer)==null?void 0:T.id])==null?void 0:b.value;if(!p){this.debug&&console.warn(`Missing alias ${(w=(m=s.format)==null?void 0:m.alias_pointer)==null?void 0:w.id} from ${E(r,e)} ${r.id}`);continue}a+=`${o}${o}[${E(p,e)}](${A(p.id,e)})${o}`;break}case"image":{let p=s.properties.caption?O(s.properties.caption):"";a+=`${o}![${p}](${ne((y=s.format)==null?void 0:y.display_source,s)})`;break}case"video":a+=`${o}<video src="${s.format.display_source} />`;break;case"file":a+=`${o}[File](${(M=s.format)==null?void 0:M.display_source})`;break;case"pdf":a+=`${o}<iframe src="${(P=s.format)==null?void 0:P.display_source}"/>`;break;case"divider":a+=`${o}---`;break;case"column_list":break;case"column":break;default:a+=`${o}`}if(s.content&&s.type!=="page"&&s.type!=="collection_view_page"){let p=["toggle","transclusion_container","transclusion_reference","column_list"].includes(s.type)?o:`
15
- ${o.trim()}> `;a+=await this.childrenToMd(s,e,p,r),s.type==="column"&&(a+=`
16
- `)}s.type==="toggle"&&(a+=`${o}</details>${o}`)}return a}async decorationsToMarkdown(t,e,o=""){var n,d,g;if(!t)return"";let r="";for(let h of t){let u="",[l,T]=h;if(!T)r+=l;else{let b=l;for(let w of T)switch(w[0]){case"p":{let y=w[1],M=await this.getBlock(y,e,`"p" ${D(e)}`);if(!M)break;let P=E(M,e),S=A(y,e);b=`[${P}](${S})`;break}case"a":{let y=w[1];b=`[${l}](${y})`;break}case"i":u+="*";break;case"b":u+="**";break;case"h":u+="";break;case"c":u+="`";break;case"s":u+="~~";break;case"e":u+="$",b=w[1];break;case"eoi":try{let y=w[1],M=await this.getBlock(y,e,`"eoi" ${D(e)}`);if(!M)break;let P=M.format.uri,S=M.format.attributes?(g=(d=(n=M.format.attributes)==null?void 0:n.filter(s=>s.id==="title")[0])==null?void 0:d.values)==null?void 0:g[0]:P;if(!P)break;b=`[${S}](${P})`;break}catch(y){console.error(y,h);break}case"u":{let y=await this.getUser(w[1],e);if(!y)break;b=`[@${y.name}](mailto:${y.email})`;break}}let m=b;T.find(w=>w[0]==="_")&&(m=`<u>${b}</u>`),m=u+m+u.split("").reverse().join(""),r+=m}}return r.split(`
17
- `).map(h=>o+h).join("")}async getBlock(t,e,o=""){var a,i,n,d,g;let r=(a=e.block[t])==null?void 0:a.value;!r&&this.recordMap&&(r=(i=this.recordMap.block[t])==null?void 0:i.value);try{!r&&this.token&&(r=(g=(d=(n=(await new j({authToken:this.token}).getBlocks([t])).recordMap)==null?void 0:n.block)==null?void 0:d[t])==null?void 0:g.value)}catch{r||this.debug&&console.warn(`${o} Missing block ${t}`)}return r&&(e.block[t]={value:r,role:"reader"},this.recordMap&&(this.recordMap.block[t]={value:r,role:"reader"})),r}async getUser(t,e){var r,a,i,n,d;let o=(r=e.notion_user[t])==null?void 0:r.value;!o&&this.recordMap&&(o=(a=this.recordMap.notion_user[t])==null?void 0:a.value);try{!o&&this.token&&(o=(d=(n=(i=(await new j({authToken:this.token}).getUsers([t])).recordMapWithRoles)==null?void 0:i.notion_user)==null?void 0:n[t])==null?void 0:d.value)}catch{o||this.debug&&console.warn(`Missing user ${t}`)}return o&&(e.notion_user[t]={value:o,role:"reader"},this.recordMap&&(this.recordMap.notion_user[t]={value:o,role:"reader"})),o}async getCollection(t,e,o=""){var i,n,d,g,h;let r=t.collection_id,a=(i=e.collection[t.collection_id])==null?void 0:i.value;if(!a&&this.recordMap&&(a=(n=this.recordMap.collection[r])==null?void 0:n.value,a)){e.collection[r]=(d=this.recordMap.collection)==null?void 0:d[r];for(let u of t.view_ids)e.collection_view[u]=(g=this.recordMap.collection_view)==null?void 0:g[u]}try{if(!a&&this.token){let l=await new j({authToken:this.token}).getPageRaw(t.id);he(1e3*this.wait),l.recordMap||console.error(l),a=(h=l.recordMap.collection[r])==null?void 0:h.value,a&&(e.collection_view={...e.collection_view,...l.recordMap.collection_view},e.collection={...e.collection,...l.recordMap.collection},e.block={...e.block,...l.recordMap.block},this.recordMap.collection_view={...this.recordMap.collection_view,...l.recordMap.collection_view},this.recordMap.collection={...this.recordMap.collection,...l.recordMap.collection},this.recordMap.block={...this.recordMap.block,...l.recordMap.block})}}catch{a||this.debug&&console.warn(`${o} Missing collection block ${t.id}`)}return await this.getCollectionView(r,t.view_ids[0],e,o),a}async getCollectionView(t,e,o,r=""){var i,n,d,g,h,u,l,T,b,m,w,y,M,P,S,s,v,p,R;let a=(d=(n=(i=o.collection_query)==null?void 0:i[t])==null?void 0:n[e])==null?void 0:d.collection_group_results;!a&&this.recordMap&&(a=(u=(h=(g=this.recordMap.collection_query)==null?void 0:g[t])==null?void 0:h[e])==null?void 0:u.collection_group_results,a&&(o.collection_query[t]={...o.collection_query[t],[e]:(T=(l=this.recordMap.collection_query)==null?void 0:l[t])==null?void 0:T[e]},this.recordMap.collection_query[t]={...this.recordMap.collection_query[t],[e]:(m=(b=this.recordMap.collection_query)==null?void 0:b[t])==null?void 0:m[e]},o.collection[t]={...o.collection[t],[e]:(y=(w=this.recordMap.collection)==null?void 0:w[t])==null?void 0:y[e]},this.recordMap.collection[t]={...this.recordMap.collection[t],[e]:(P=(M=this.recordMap.collection)==null?void 0:M[t])==null?void 0:P[e]}));try{if(!a&&this.token){let f=await new j({authToken:this.token}).getCollectionData(t,e,(S=o.collection_view[e])==null?void 0:S.value);if(a=(v=(s=f.result)==null?void 0:s.reducerResults)==null?void 0:v.collection_group_results,a){o.collection_query[t]={...o.collection_query[t],[e]:(p=f.result)==null?void 0:p.reducerResults},this.recordMap&&(this.recordMap.collection_query[t]={...this.recordMap.collection_query[t],[e]:(R=f.result)==null?void 0:R.reducerResults});for(let k in f.recordMap.block){let _=f.recordMap.block[k].value;_&&(o.block[k]={value:_,role:"reader"},this.recordMap&&(this.recordMap.block[k]={value:_,role:"reader"}))}for(let k in f.recordMap.collection){let _=f.recordMap.collection[k].value;_&&(o.collection[k]={value:_,role:"reader"},this.recordMap&&(this.recordMap.collection[k]={value:_,role:"reader"}))}for(let k in f.recordMap.collection_view){let _=f.recordMap.collection_view[k].value;_&&(o.collection_view[k]={value:_,role:"reader"},this.recordMap&&(this.recordMap.collection_view[k]={value:_,role:"reader"}))}}}}catch{a||this.debug&&console.warn(`${r} Missing collection view ${e}`)}return a}async getSpace(t,e){var r,a,i,n,d;let o=(r=e.space[t])==null?void 0:r.value;!o&&this.recordMap&&(o=(a=this.recordMap.space[t])==null?void 0:a.value);try{!o&&this.token&&(o=(d=(n=(i=(await new j({authToken:this.token}).getSpaces([t])).recordMapWithRoles)==null?void 0:i.space)==null?void 0:n[t])==null?void 0:d.value,o&&(e.space[t]={value:o,role:"reader"},this.recordMap&&(this.recordMap.space[t]={value:o,role:"reader"})))}catch{o||this.debug&&console.warn(`Missing space ${t}`)}return o}};async function pe(c){let t=[];t.push(N(x(c,"recordMap","block.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"recordMap","collection.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"recordMap","notion_user.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"recordMap","space.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"recordMap","collection_view.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"recordMap","collection_query.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"recordMap","signed_urls.json"),"utf8").then(JSON.parse)),t.push(N(x(c,"pageTree.json"),"utf8").then(JSON.parse));let[e,o,r,a,i,n,d,g]=await Promise.all(t),h={},u=L.createReadStream(x(c,"pageMap.json")),l=F.parse("*");return u.pipe(l),l.on("data",b=>{let m=Object.keys(b.block)[0];h[m]=b}),await new Promise(b=>X.finished(l,m=>b(m))),{recordMap:{block:e,collection:o,notion_user:r,space:a,collection_query:n,collection_view:i,signed_urls:d},pageTree:g,pageMap:h}}async function Ee(c,t){let e={},o=L.createReadStream(x(c,`${t}.json`)),r=F.parse("*");return o.pipe(r),r.on("*",([a,i])=>{e[a]=i}),new Promise(a=>X.finished(r,i=>{console.error(i),a(e)}))}var he=c=>{let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,c)};import me from"fs";import{promisify as fe}from"util";var ge=fe(me.writeFile);async function ee(c,t){let e=Z(t,"pages"),o="Texonom PageTree",r=`${c}/pagetree.html`;await I(e,o,r);let a=Z(t,"blocks"),i="Texonom BlockMap",n=`${c}/blocktree.html`;await I(a,i,n)}function Z(c,t){function e(o){let r=o.children?o.children.map(e).filter(i=>i!==null):[],a=o[t]||0;if(r.length>0){let i=r.reduce((n,d)=>n+d.value,0);a===0&&(a=i)}return a<=0?null:{id:o.id,name:o.title,value:a,children:r.length>0?r:void 0}}return e(c)}async function I(c,t,e){let o=`
1
+ import { Command as tt, Option as k, Cli as Q, Builtins as X } from "clipanion";
2
+ import { NotionAPI as N } from "@texonom/nclient";
3
+ import { parsePageId as V, getBlockTitle as B, recursivePageTree as et, getAllInSpace as at, getCanonicalPageId as z, getBlockParent as it, getTextContent as R, formatDate as H, defaultMapImageUrl as ot, getPageTitle as L } from "@texonom/nutils";
4
+ import { join as x } from "path";
5
+ import { mkdir as q, readFile as j } from "fs/promises";
6
+ import D from "JSONStream";
7
+ import J from "graceful-fs";
8
+ import { promisify as Z } from "util";
9
+ import { execSync as rt } from "child_process";
10
+ import I from "stream";
11
+ import { format as nt } from "prettier";
12
+ import { isSpace as st, isCollection as W } from "@texonom/ntypes";
13
+ import ct from "fs";
14
+ const lt = "Notion CLI", dt = "1.5.1";
15
+ let G = Z(J.writeFile);
16
+ const A = (l, t, e = "https://texonom.com") => `${e}/${z(l, t)}`;
17
+ class ht {
18
+ constructor(t) {
19
+ this.promises = [], this.folder = "texonom-raw", this.md = "texonom-md", this.domain = "https://texonom.com", this.validation = !0, this.update = !1, this.recursive = !1, this.prefetch = !1, this.load = !1, this.raw = !1, this.dataset = !1, this.push = !1, this.debug = !1, this.wait = 5, this.page = V(t.page), this.folder = t.folder ?? this.folder, this.domain = t.domain ?? this.domain, this.md = t.md ?? this.md, this.validation = t.validation ?? this.validation, this.update = t.update ?? this.update, this.recursive = t.recursive ?? this.recursive, this.prefetch = t.prefetch ?? this.prefetch, this.load = t.load ?? this.load, this.raw = t.raw ?? this.raw, this.dataset = t.dataset ?? this.dataset, this.token = t.token, this.push = t.push ?? this.push, this.notion = new N({ authToken: this.token }), this.validation && (G = async () => {
20
+ });
21
+ }
22
+ async execute() {
23
+ const t = V(this.page);
24
+ if (this.load && (console.time("Load raw data"), await this.loadRaw(), console.timeEnd("Load raw data")), this.prefetch && (console.time("Fetch raw data"), await this.fetchRawSpace(t), console.timeEnd("Fetch raw data")), this.raw)
25
+ console.time("Export raw files"), this.recursive ? await this.saveRawSpace() : await this.saveRawPage(t), console.timeEnd("Export raw files");
26
+ else {
27
+ console.time("Extract markdown"), await this.exportMd(t), console.timeEnd("Extract markdown");
28
+ const e = {
29
+ id: this.page,
30
+ title: B(this.recordMap.block[this.page].value, this.recordMap),
31
+ blocks: 1,
32
+ pages: 1,
33
+ children: [],
34
+ type: "page"
35
+ };
36
+ et(this.recordMap, e), this.pageTree = e;
37
+ }
38
+ await Promise.all(this.promises), this.update && (this.recursive ? await this.saveRawSpace() : await this.saveRawPage(t));
39
+ }
40
+ async loadRaw() {
41
+ const { recordMap: t, pageTree: e, pageMap: a } = await ut(this.folder);
42
+ this.recordMap = t, this.pageTree = e, this.pageMap = a;
43
+ }
44
+ async fetchRawSpace(t) {
45
+ const { recordMap: e, pageTree: a, pageMap: o } = await at(
46
+ t,
47
+ this.notion.getPage.bind(this.notion),
48
+ this.notion.getBlocks.bind(this.notion),
49
+ this.notion.fetchCollections.bind(this.notion),
50
+ {
51
+ startRecordMap: this.recordMap,
52
+ collectionConcurrency: 100,
53
+ concurrency: 100,
54
+ fetchOption: { timeout: 1e4 },
55
+ debug: this.debug
56
+ }
57
+ );
58
+ this.pageMap = o, this.recordMap = e, this.pageTree = a;
59
+ }
60
+ async saveRawSpace() {
61
+ if (this.validation) return;
62
+ await q(this.folder, { recursive: !0 });
63
+ const t = [];
64
+ await q(x(this.folder, "recordMap"), { recursive: !0 });
65
+ for (const e in this.recordMap) this.saveJson(x("recordMap", e), this.recordMap[e]);
66
+ this.saveJson("pageMap", this.pageMap), this.saveJson("pageTree", this.pageTree), await Promise.all(t);
67
+ }
68
+ saveJson(t, e) {
69
+ if (this.validation) return;
70
+ const a = J.createWriteStream(`${x(this.folder, t)}.json`), o = D.stringifyObject();
71
+ o.pipe(a);
72
+ for (const i in e) o.write([i, e[i]]);
73
+ o.end();
74
+ }
75
+ async saveRawPage(t) {
76
+ if (this.validation) return;
77
+ await q(this.folder, { recursive: !0 });
78
+ const e = await this.notion.getPage(t), a = `${z(t, e)}`;
79
+ let o = JSON.stringify(e);
80
+ const i = "json";
81
+ o = await nt(o, { parser: "json" }), await this.writeFile(`${x(this.folder, a)}.${i}`, o);
82
+ }
83
+ async writeFile(t, e) {
84
+ if (this.folder) await G(t, e);
85
+ else return;
86
+ }
87
+ async exportMd(t) {
88
+ await q(this.md, { recursive: !0 });
89
+ try {
90
+ let e = this.pageMap && this.pageMap[t];
91
+ e || (console.warn(`Missing from pageMap ${t}`), e = await this.notion.getPage(t)), this.recursive || (this.recordMap = e);
92
+ try {
93
+ e || (e = await this.notion.getPage(t));
94
+ } catch {
95
+ return;
96
+ }
97
+ if (!["page", "collection_view_page"].includes(e.block[t].value.type)) throw new Error("Not a page");
98
+ const a = await this.pageToMarkdown(t, e);
99
+ this.pageMap[t] || (this.pageMap[t] = e);
100
+ const o = x(this.md, `${z(t, e)}`);
101
+ this.promises.push(this.writeFile(`${o}.md`, a));
102
+ } catch (e) {
103
+ console.error(t, e);
104
+ }
105
+ }
106
+ async pageToMarkdown(t, e) {
107
+ const a = await this.pageToMarkdownObj(t, e);
108
+ let o = `---
109
+ Title: ${a.title}
110
+ `;
111
+ o += `Parent: ${a.parent}
112
+ `;
113
+ const i = Object.keys(a).filter((r) => !["title", "parent", "body"].includes(r));
114
+ for (const r of i) o += `${r}: ${a[r]}
115
+ `;
116
+ return o += `---
117
+ `, o += a.body, o;
118
+ }
119
+ async pageToMarkdownObj(t, e) {
120
+ var g, p;
121
+ const a = e.block[t].value, o = {}, i = await this.decorationsToMarkdown(
122
+ (g = a.properties) != null && g.title ? a.properties.title : [["Untitled"]],
123
+ e
124
+ );
125
+ o.title = i;
126
+ const r = it(a, e);
127
+ let n;
128
+ if (st(r) ? n = r.name : W(r) ? n = R(r.name) : r && (n = B(r, e)), W(n)) {
129
+ const h = n != null && n.schema ? Object.keys(n.schema) : [];
130
+ h.splice(h.indexOf("title"), 1);
131
+ for (const c of h) {
132
+ const T = n.schema[c].name, w = n.schema[c].type;
133
+ let m = "";
134
+ switch (w) {
135
+ case "text":
136
+ m = (p = a == null ? void 0 : a.properties) != null && p[c] ? await this.decorationsToMarkdown(a.properties[c], e) : "";
137
+ break;
138
+ case "created_by": {
139
+ const b = await this.getUser(a.created_by_id, e);
140
+ m = b ? b.name : "Unknown";
141
+ break;
142
+ }
143
+ case "last_edited_by": {
144
+ const b = await this.getUser(a.last_edited_by_id, e);
145
+ m = b ? b.name : "Unknown";
146
+ break;
147
+ }
148
+ case "created_time":
149
+ m = H(a.created_time);
150
+ break;
151
+ case "last_edited_time":
152
+ m = H(a.last_edited_time);
153
+ break;
154
+ default:
155
+ m = "";
156
+ }
157
+ o[T] = m;
158
+ }
159
+ }
160
+ const d = await this.childrenToMd(a, e, "", a);
161
+ return o.body = d, o;
162
+ }
163
+ async childrenToMd(t, e, a, o) {
164
+ var n, d, g, p, h, c, T, w, m, b, v, _, S;
165
+ let i = "", r = 1;
166
+ for (const P of t.content ? t.content : []) {
167
+ const s = await this.getBlock(P, e, `${P} from ${B(o, e)}`);
168
+ if (!s) continue;
169
+ const $ = (n = s == null ? void 0 : s.properties) == null ? void 0 : n.title;
170
+ switch (s.type) {
171
+ case "header":
172
+ i += `${a}# ${await this.decorationsToMarkdown($, e)}`;
173
+ break;
174
+ case "sub_header":
175
+ i += `${a}## ${await this.decorationsToMarkdown($, e)}`;
176
+ break;
177
+ case "sub_sub_header":
178
+ i += `${a}### ${await this.decorationsToMarkdown($, e)}`;
179
+ break;
180
+ case "text":
181
+ i += `${a}${await this.decorationsToMarkdown($, e)}`;
182
+ break;
183
+ case "bulleted_list":
184
+ i += `${a}- ${await this.decorationsToMarkdown($, e)}`;
185
+ break;
186
+ case "numbered_list":
187
+ i += `${a}${r++}. ${await this.decorationsToMarkdown($, e)}`;
188
+ break;
189
+ case "to_do":
190
+ i += `${a}- [ ] ${await this.decorationsToMarkdown($, e)}`;
191
+ break;
192
+ case "toggle":
193
+ i += `${a}<details><summary>${a}${a}${await this.decorationsToMarkdown(
194
+ $,
195
+ e
196
+ )}</summary>
197
+ `;
198
+ break;
199
+ case "quote":
200
+ i += await this.decorationsToMarkdown($, e, `
201
+ ${a.trim()}> `) + `
202
+ `;
203
+ break;
204
+ case "code":
205
+ i += `${a}\`\`\`type${await this.decorationsToMarkdown($, e)}\`\`\``;
206
+ break;
207
+ case "equation":
208
+ i += `${a}$$${await this.decorationsToMarkdown($, e)}$$`;
209
+ break;
210
+ case "callout": {
211
+ i += await this.decorationsToMarkdown($, e, `
212
+ ${a.trim()}> `) + `
213
+ `;
214
+ break;
215
+ }
216
+ case "bookmark": {
217
+ const u = `
218
+ ${a.trim()}> `;
219
+ i += `${u}[${R(
220
+ (d = s.properties) != null && d.title ? s.properties.title : [["Untitled"]]
221
+ )}](${R(s.properties.link)})
222
+ `;
223
+ break;
224
+ }
225
+ case "external_object_instance":
226
+ try {
227
+ const u = s.format.original_url, O = s.format.attributes ? (p = (g = s.format.attributes.filter((E) => E.id === "title")[0]) == null ? void 0 : g.values) == null ? void 0 : p[0] : u;
228
+ if (!u) break;
229
+ i += `${a}${a}[${O}](${u})${a}`;
230
+ break;
231
+ } catch (u) {
232
+ console.error(u, s.id);
233
+ break;
234
+ }
235
+ // Collection
236
+ case "collection_view_page":
237
+ case "collection_view": {
238
+ const u = await this.getCollection(
239
+ s,
240
+ e,
241
+ `${s.id} from ${L(e)}`
242
+ );
243
+ if (!u) continue;
244
+ i += `${a}### ${await this.decorationsToMarkdown(u.name, e)}`, i += `${a}|Title|
245
+ |:-:|`;
246
+ const O = s.view_ids.map((f) => {
247
+ var y;
248
+ return e.collection_view[f] || this.debug && console.warn(`Missing view ${f} from ${u.name}`), (y = e.collection_view[f]) == null ? void 0 : y.value;
249
+ }).filter(Boolean), E = [];
250
+ for (const f of O) {
251
+ const y = await this.getCollectionView(
252
+ u.id,
253
+ f.id,
254
+ e,
255
+ `${u.name} ${f.name}`
256
+ );
257
+ if (y) for (const M of y.blockIds) E.push(M);
258
+ else break;
259
+ }
260
+ for (const f of E) {
261
+ const y = (h = e.block[f]) == null ? void 0 : h.value;
262
+ y || this.debug && console.warn(`no ${f} in ${u.name[0]}`), i += `${a}|[${B(y, e)}](${A(f, e)})|`;
263
+ }
264
+ if (this.recursive && E.length)
265
+ for (const f of E) this.promises.push(this.exportMd(f));
266
+ break;
267
+ }
268
+ case "page": {
269
+ i += `${a}${a}[${B(s, e)}](${A(
270
+ s.id,
271
+ e
272
+ )})${a}`, this.recursive && this.promises.push(this.exportMd(s.id));
273
+ break;
274
+ }
275
+ case "alias": {
276
+ const u = (w = e.block[(T = (c = s.format) == null ? void 0 : c.alias_pointer) == null ? void 0 : T.id]) == null ? void 0 : w.value;
277
+ if (!u) {
278
+ this.debug && console.warn(
279
+ `Missing alias ${(b = (m = s.format) == null ? void 0 : m.alias_pointer) == null ? void 0 : b.id} from ${B(o, e)} ${o.id}`
280
+ );
281
+ continue;
282
+ }
283
+ i += `${a}${a}[${B(u, e)}](${A(
284
+ u.id,
285
+ e
286
+ )})${a}`;
287
+ break;
288
+ }
289
+ // Media
290
+ case "image": {
291
+ const u = s.properties.caption ? R(s.properties.caption) : "";
292
+ i += `${a}![${u}](${ot((v = s.format) == null ? void 0 : v.display_source, s)})`;
293
+ break;
294
+ }
295
+ case "video":
296
+ i += `${a}<video src="${s.format.display_source} />`;
297
+ break;
298
+ // Embed
299
+ case "file":
300
+ i += `${a}[File](${(_ = s.format) == null ? void 0 : _.display_source})`;
301
+ break;
302
+ case "pdf":
303
+ i += `${a}<iframe src="${(S = s.format) == null ? void 0 : S.display_source}"/>`;
304
+ break;
305
+ // Else
306
+ case "divider":
307
+ i += `${a}---`;
308
+ break;
309
+ case "column_list":
310
+ break;
311
+ case "column":
312
+ break;
313
+ default:
314
+ i += `${a}`;
315
+ }
316
+ if (s.content && s.type !== "page" && s.type !== "collection_view_page") {
317
+ const u = ["toggle", "transclusion_container", "transclusion_reference", "column_list"].includes(
318
+ s.type
319
+ ) ? a : `
320
+ ${a.trim()}> `;
321
+ i += await this.childrenToMd(s, e, u, o), s.type === "column" && (i += `
322
+ `);
323
+ }
324
+ s.type === "toggle" && (i += `${a}</details>${a}`);
325
+ }
326
+ return i;
327
+ }
328
+ async decorationsToMarkdown(t, e, a = "") {
329
+ var n, d, g;
330
+ if (!t) return "";
331
+ let o = "";
332
+ for (const p of t) {
333
+ let h = "";
334
+ const [c, T] = p;
335
+ if (!T)
336
+ o += c;
337
+ else {
338
+ let w = c;
339
+ for (const b of T)
340
+ switch (b[0]) {
341
+ case "p": {
342
+ const v = b[1], _ = await this.getBlock(v, e, `"p" ${L(e)}`);
343
+ if (!_) break;
344
+ const S = B(_, e), P = A(v, e);
345
+ w = `[${S}](${P})`;
346
+ break;
347
+ }
348
+ case "a": {
349
+ const v = b[1];
350
+ w = `[${c}](${v})`;
351
+ break;
352
+ }
353
+ case "i":
354
+ h += "*";
355
+ break;
356
+ case "b":
357
+ h += "**";
358
+ break;
359
+ case "h":
360
+ h += "";
361
+ break;
362
+ case "c":
363
+ h += "`";
364
+ break;
365
+ case "s":
366
+ h += "~~";
367
+ break;
368
+ case "e":
369
+ h += "$", w = b[1];
370
+ break;
371
+ case "eoi":
372
+ try {
373
+ const v = b[1], _ = await this.getBlock(v, e, `"eoi" ${L(e)}`);
374
+ if (!_) break;
375
+ const S = _.format.uri, P = _.format.attributes ? (g = (d = (n = _.format.attributes) == null ? void 0 : n.filter((s) => s.id === "title")[0]) == null ? void 0 : d.values) == null ? void 0 : g[0] : S;
376
+ if (!S) break;
377
+ w = `[${P}](${S})`;
378
+ break;
379
+ } catch (v) {
380
+ console.error(v, p);
381
+ break;
382
+ }
383
+ case "u": {
384
+ const v = await this.getUser(b[1], e);
385
+ if (!v) break;
386
+ w = `[@${v.name}](mailto:${v.email})`;
387
+ break;
388
+ }
389
+ }
390
+ let m = w;
391
+ T.find((b) => b[0] === "_") && (m = `<u>${w}</u>`), m = h + m + h.split("").reverse().join(""), o += m;
392
+ }
393
+ }
394
+ return o.split(`
395
+ `).map((p) => a + p).join("");
396
+ }
397
+ async getBlock(t, e, a = "") {
398
+ var i, r, n, d, g;
399
+ let o = (i = e.block[t]) == null ? void 0 : i.value;
400
+ !o && this.recordMap && (o = (r = this.recordMap.block[t]) == null ? void 0 : r.value);
401
+ try {
402
+ !o && this.token && (o = (g = (d = (n = (await new N({ authToken: this.token }).getBlocks([t])).recordMap) == null ? void 0 : n.block) == null ? void 0 : d[t]) == null ? void 0 : g.value);
403
+ } catch {
404
+ o || this.debug && console.warn(`${a} Missing block ${t}`);
405
+ }
406
+ return o && (e.block[t] = { value: o, role: "reader" }, this.recordMap && (this.recordMap.block[t] = { value: o, role: "reader" })), o;
407
+ }
408
+ async getUser(t, e) {
409
+ var o, i, r, n, d;
410
+ let a = (o = e.notion_user[t]) == null ? void 0 : o.value;
411
+ !a && this.recordMap && (a = (i = this.recordMap.notion_user[t]) == null ? void 0 : i.value);
412
+ try {
413
+ !a && this.token && (a = (d = (n = (r = (await new N({ authToken: this.token }).getUsers([t])).recordMapWithRoles) == null ? void 0 : r.notion_user) == null ? void 0 : n[t]) == null ? void 0 : d.value);
414
+ } catch {
415
+ a || this.debug && console.warn(`Missing user ${t}`);
416
+ }
417
+ return a && (e.notion_user[t] = { value: a, role: "reader" }, this.recordMap && (this.recordMap.notion_user[t] = { value: a, role: "reader" })), a;
418
+ }
419
+ async getCollection(t, e, a = "") {
420
+ var r, n, d, g, p;
421
+ const o = t.collection_id;
422
+ let i = (r = e.collection[t.collection_id]) == null ? void 0 : r.value;
423
+ if (!i && this.recordMap && (i = (n = this.recordMap.collection[o]) == null ? void 0 : n.value, i)) {
424
+ e.collection[o] = (d = this.recordMap.collection) == null ? void 0 : d[o];
425
+ for (const h of t.view_ids)
426
+ e.collection_view[h] = (g = this.recordMap.collection_view) == null ? void 0 : g[h];
427
+ }
428
+ try {
429
+ if (!i && this.token) {
430
+ const c = await new N({ authToken: this.token }).getPageRaw(t.id);
431
+ pt(1e3 * this.wait), c.recordMap || console.error(c), i = (p = c.recordMap.collection[o]) == null ? void 0 : p.value, i && (e.collection_view = { ...e.collection_view, ...c.recordMap.collection_view }, e.collection = { ...e.collection, ...c.recordMap.collection }, e.block = { ...e.block, ...c.recordMap.block }, this.recordMap.collection_view = { ...this.recordMap.collection_view, ...c.recordMap.collection_view }, this.recordMap.collection = { ...this.recordMap.collection, ...c.recordMap.collection }, this.recordMap.block = { ...this.recordMap.block, ...c.recordMap.block });
432
+ }
433
+ } catch {
434
+ i || this.debug && console.warn(`${a} Missing collection block ${t.id}`);
435
+ }
436
+ return await this.getCollectionView(o, t.view_ids[0], e, a), i;
437
+ }
438
+ async getCollectionView(t, e, a, o = "") {
439
+ var r, n, d, g, p, h, c, T, w, m, b, v, _, S, P, s, $, u, O;
440
+ let i = (d = (n = (r = a.collection_query) == null ? void 0 : r[t]) == null ? void 0 : n[e]) == null ? void 0 : d.collection_group_results;
441
+ !i && this.recordMap && (i = (h = (p = (g = this.recordMap.collection_query) == null ? void 0 : g[t]) == null ? void 0 : p[e]) == null ? void 0 : h.collection_group_results, i && (a.collection_query[t] = {
442
+ ...a.collection_query[t],
443
+ [e]: (T = (c = this.recordMap.collection_query) == null ? void 0 : c[t]) == null ? void 0 : T[e]
444
+ }, this.recordMap.collection_query[t] = {
445
+ ...this.recordMap.collection_query[t],
446
+ [e]: (m = (w = this.recordMap.collection_query) == null ? void 0 : w[t]) == null ? void 0 : m[e]
447
+ }, a.collection[t] = {
448
+ ...a.collection[t],
449
+ [e]: (v = (b = this.recordMap.collection) == null ? void 0 : b[t]) == null ? void 0 : v[e]
450
+ }, this.recordMap.collection[t] = {
451
+ ...this.recordMap.collection[t],
452
+ [e]: (S = (_ = this.recordMap.collection) == null ? void 0 : _[t]) == null ? void 0 : S[e]
453
+ }));
454
+ try {
455
+ if (!i && this.token) {
456
+ const f = await new N({ authToken: this.token }).getCollectionData(t, e, (P = a.collection_view[e]) == null ? void 0 : P.value);
457
+ if (i = ($ = (s = f.result) == null ? void 0 : s.reducerResults) == null ? void 0 : $.collection_group_results, i) {
458
+ a.collection_query[t] = {
459
+ ...a.collection_query[t],
460
+ [e]: (u = f.result) == null ? void 0 : u.reducerResults
461
+ }, this.recordMap && (this.recordMap.collection_query[t] = {
462
+ ...this.recordMap.collection_query[t],
463
+ [e]: (O = f.result) == null ? void 0 : O.reducerResults
464
+ });
465
+ for (const y in f.recordMap.block) {
466
+ const M = f.recordMap.block[y].value;
467
+ M && (a.block[y] = { value: M, role: "reader" }, this.recordMap && (this.recordMap.block[y] = { value: M, role: "reader" }));
468
+ }
469
+ for (const y in f.recordMap.collection) {
470
+ const M = f.recordMap.collection[y].value;
471
+ M && (a.collection[y] = { value: M, role: "reader" }, this.recordMap && (this.recordMap.collection[y] = { value: M, role: "reader" }));
472
+ }
473
+ for (const y in f.recordMap.collection_view) {
474
+ const M = f.recordMap.collection_view[y].value;
475
+ M && (a.collection_view[y] = { value: M, role: "reader" }, this.recordMap && (this.recordMap.collection_view[y] = { value: M, role: "reader" }));
476
+ }
477
+ }
478
+ }
479
+ } catch {
480
+ i || this.debug && console.warn(`${o} Missing collection view ${e}`);
481
+ }
482
+ return i;
483
+ }
484
+ async getSpace(t, e) {
485
+ var o, i, r, n, d;
486
+ let a = (o = e.space[t]) == null ? void 0 : o.value;
487
+ !a && this.recordMap && (a = (i = this.recordMap.space[t]) == null ? void 0 : i.value);
488
+ try {
489
+ !a && this.token && (a = (d = (n = (r = (await new N({ authToken: this.token }).getSpaces([t])).recordMapWithRoles) == null ? void 0 : r.space) == null ? void 0 : n[t]) == null ? void 0 : d.value, a && (e.space[t] = { value: a, role: "reader" }, this.recordMap && (this.recordMap.space[t] = { value: a, role: "reader" })));
490
+ } catch {
491
+ a || this.debug && console.warn(`Missing space ${t}`);
492
+ }
493
+ return a;
494
+ }
495
+ pushRepos() {
496
+ const t = (a, o) => {
497
+ try {
498
+ rt(a, { cwd: o, stdio: "ignore" });
499
+ } catch {
500
+ }
501
+ }, e = (/* @__PURE__ */ new Date()).toString();
502
+ t("git init", this.folder), t("git add .", this.folder), t(`git commit -m "${e}"`, this.folder), t("git branch -M main", this.folder), t("git remote add origin https://github.com/texonom/texonom-raw.git", this.folder), t("git push -u origin main --force", this.folder), t("git init", this.md), t("git add .", this.md), t(`git commit -m "${e}"`, this.md), t("git branch -M main", this.md), t("git remote add origin https://github.com/texonom/texonom-md.git", this.md), t("git push -u origin main --force", this.md);
503
+ }
504
+ }
505
+ async function ut(l) {
506
+ const t = [];
507
+ t.push(j(x(l, "recordMap", "block.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "recordMap", "collection.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "recordMap", "notion_user.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "recordMap", "space.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "recordMap", "collection_view.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "recordMap", "collection_query.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "recordMap", "signed_urls.json"), "utf8").then(JSON.parse)), t.push(j(x(l, "pageTree.json"), "utf8").then(JSON.parse));
508
+ const [e, a, o, i, r, n, d, g] = await Promise.all(t), p = {}, h = J.createReadStream(x(l, "pageMap.json")), c = D.parse("*");
509
+ return h.pipe(c), c.on("data", (w) => {
510
+ const m = Object.keys(w.block)[0];
511
+ p[m] = w;
512
+ }), await new Promise((w) => I.finished(c, (m) => w(m))), { recordMap: {
513
+ block: e,
514
+ collection: a,
515
+ notion_user: o,
516
+ space: i,
517
+ collection_query: n,
518
+ collection_view: r,
519
+ signed_urls: d
520
+ }, pageTree: g, pageMap: p };
521
+ }
522
+ async function Et(l, t) {
523
+ const e = {}, a = J.createReadStream(x(l, `${t}.json`)), o = D.parse("*");
524
+ return a.pipe(o), o.on("*", ([i, r]) => {
525
+ e[i] = r;
526
+ }), new Promise(
527
+ (i) => I.finished(o, (r) => {
528
+ console.error(r), i(e);
529
+ })
530
+ );
531
+ }
532
+ const pt = (l) => {
533
+ const t = new Int32Array(new SharedArrayBuffer(4));
534
+ Atomics.wait(t, 0, 0, l);
535
+ }, mt = Z(ct.writeFile);
536
+ async function ft(l, t) {
537
+ const e = Y(t, "pages"), a = "Texonom PageTree", o = `${l}/pagetree.html`;
538
+ await K(e, a, o);
539
+ const i = Y(t, "blocks"), r = "Texonom BlockMap", n = `${l}/blocktree.html`;
540
+ await K(i, r, n);
541
+ }
542
+ function Y(l, t) {
543
+ function e(a) {
544
+ const o = a.children ? a.children.map(e).filter((r) => r !== null) : [];
545
+ let i = a[t] || 0;
546
+ if (o.length > 0) {
547
+ const r = o.reduce((n, d) => n + d.value, 0);
548
+ i === 0 && (i = r);
549
+ }
550
+ return i <= 0 ? null : {
551
+ id: a.id,
552
+ name: a.title,
553
+ value: i,
554
+ children: o.length > 0 ? o : void 0
555
+ };
556
+ }
557
+ return e(l);
558
+ }
559
+ async function K(l, t, e) {
560
+ const a = `
18
561
  <!DOCTYPE html>
19
562
  <html lang="en">
20
563
  <head>
@@ -74,9 +617,9 @@ ${o.trim()}> `;a+=await this.childrenToMd(s,e,p,r),s.type==="column"&&(a+=`
74
617
  <div class="breadcrumb" id="breadcrumb"></div>
75
618
  <div class="current-title" id="current-title"></div>
76
619
  <div class="chart" id="chart"></div>
77
- <script src="https://d3js.org/d3.v6.min.js"></script>
620
+ <script src="https://d3js.org/d3.v6.min.js"><\/script>
78
621
  <script>
79
- var data = ${JSON.stringify(c)};
622
+ var data = ${JSON.stringify(l)};
80
623
 
81
624
  var margin = {top: 20, right: 0, bottom: 0, left: 0},
82
625
  width = document.getElementById('chart').clientWidth,
@@ -298,9 +841,101 @@ ${o.trim()}> `;a+=await this.childrenToMd(s,e,p,r),s.type==="column"&&(a+=`
298
841
  }
299
842
  return null;
300
843
  }
301
- </script>
844
+ <\/script>
302
845
  </body>
303
846
  </html>
304
- `;await ge(e,o,"utf8")}function te(c){let t=0,e=0,o=0;function r(a,i){if(t+=a.pages||0,e+=a.blocks||0,i>o&&(o=i),a.children)for(let n of a.children)r(n,i+1)}return r(c,1),{totalPages:t,totalBlocks:e,maxDepth:o}}async function oe(c,t){await(await import("fs/promises")).writeFile(c,JSON.stringify(t,null,2),"utf8")}var C=class extends be{constructor(){super(...arguments);this.folder=$.String("-o,--output","texonom-raw",{description:"Target root folder to export folder"});this.md=$.String("-m,--md","texonom-md",{description:"Target folder to export markdown"});this.domain=$.String("-d,--domain","https://texonom.com",{description:"Domain to fill in the link"});this.validation=$.Boolean("-v,--validation",{description:"Validation exported data only"});this.update=$.Boolean("-u,--update",{description:"Update exported data and resave to the --root"});this.page=$.String("-p,--page",{required:!0,description:"Target page to export"});this.recursive=$.Boolean("-r,--recursive",{description:"Recursively export children"});this.prefetch=$.Boolean("-f, --prefetch",{description:"Prefetch all space for faster export (recommended for exporting all pages in a space)"});this.load=$.Boolean("-l, --load",{description:"Load data from exported cache folder --root"});this.raw=$.Boolean("--raw",{description:`Export raw recordMap JSON data
305
- Markdown format do not preserve all information`});this.dataset=$.Boolean("-d, --dataset",{description:"Export as dataset for LLM learning"});this.treemap=$.Boolean("--treemap",{description:"Generate HTML treemap after export"});this.stats=$.Boolean("--stats",{description:"Generate statistics JSON after export"});this.token=$.String("-t,--token",{description:"Notion Access Token"});this.wait=$.Counter("-w,--wait",{description:"Wait couter for missed collection view"})}async execute(){let e=new J({folder:this.folder,validation:this.validation,update:this.update,page:this.page,recursive:this.recursive,prefetch:this.prefetch,load:this.load,raw:this.raw,dataset:this.dataset,token:this.token});await e.execute(),(this.treemap||this.stats)&&(e.pageTree||await e.loadRaw());let o=e.pageTree;if(this.treemap&&o&&await ee(this.folder,o),this.stats&&o){let r=te(o);await oe(`${this.folder}/stats.json`,r)}}};C.paths=[["export"]];var z=new ae({binaryName:"notion",binaryLabel:H,binaryVersion:W});z.register(C);z.register(re.HelpCommand);z.register(re.VersionCommand);z.runExit(process.argv.slice(2),ae.defaultContext);export{C as NotionExportCommand,J as NotionExporter,te as computeStats,ee as generateTreemaps,A as getBlockLink,Ee as loadJson,pe as loadRaw,oe as writeStats};
306
- //# sourceMappingURL=main.js.map
847
+ `;
848
+ await mt(e, a, "utf8");
849
+ }
850
+ function gt(l) {
851
+ let t = 0, e = 0, a = 0;
852
+ function o(i, r) {
853
+ if (t += i.pages || 0, e += i.blocks || 0, r > a && (a = r), i.children) for (const n of i.children) o(n, r + 1);
854
+ }
855
+ return o(l, 1), { totalPages: t, totalBlocks: e, maxDepth: a };
856
+ }
857
+ async function wt(l, t) {
858
+ await (await import("fs/promises")).writeFile(l, JSON.stringify(t, null, 2), "utf8");
859
+ }
860
+ const F = class F extends tt {
861
+ constructor() {
862
+ super(...arguments), this.folder = k.String("-o,--output", "texonom-raw", {
863
+ description: "Target root folder to export folder"
864
+ }), this.md = k.String("-m,--md", "texonom-md", {
865
+ description: "Target folder to export markdown"
866
+ }), this.domain = k.String("-d,--domain", "https://texonom.com", {
867
+ description: "Domain to fill in the link"
868
+ }), this.validation = k.Boolean("-v,--validation", {
869
+ description: "Validation exported data only"
870
+ }), this.update = k.Boolean("-u,--update", {
871
+ description: "Update exported data and resave to the --root"
872
+ }), this.page = k.String("-p,--page", {
873
+ required: !0,
874
+ description: "Target page to export"
875
+ }), this.recursive = k.Boolean("-r,--recursive", {
876
+ description: "Recursively export children"
877
+ }), this.prefetch = k.Boolean("-f, --prefetch", {
878
+ description: "Prefetch all space for faster export (recommended for exporting all pages in a space)"
879
+ }), this.load = k.Boolean("-l, --load", {
880
+ description: "Load data from exported cache folder --root"
881
+ }), this.raw = k.Boolean("--raw", {
882
+ description: `Export raw recordMap JSON data
883
+ Markdown format do not preserve all information`
884
+ }), this.dataset = k.Boolean("-d, --dataset", {
885
+ description: "Export as dataset for LLM learning"
886
+ }), this.treemap = k.Boolean("--treemap", {
887
+ description: "Generate HTML treemap after export"
888
+ }), this.stats = k.Boolean("--stats", {
889
+ description: "Generate statistics JSON after export"
890
+ }), this.token = k.String("-t,--token", {
891
+ description: "Notion Access Token"
892
+ }), this.wait = k.Counter("-w,--wait", {
893
+ description: "Wait couter for missed collection view"
894
+ }), this.push = k.Boolean("--push", {
895
+ description: "Push exported data to remote repositories"
896
+ });
897
+ }
898
+ async execute() {
899
+ const t = new ht({
900
+ folder: this.folder,
901
+ validation: this.validation,
902
+ update: this.update,
903
+ page: this.page,
904
+ recursive: this.recursive,
905
+ prefetch: this.prefetch,
906
+ load: this.load,
907
+ raw: this.raw,
908
+ dataset: this.dataset,
909
+ token: this.token,
910
+ push: this.push
911
+ });
912
+ await t.execute(), this.push && await t.pushRepos(), (this.treemap || this.stats) && (t.pageTree || await t.loadRaw());
913
+ const e = t.pageTree;
914
+ if (this.treemap && e && await ft(this.folder, e), this.stats && e) {
915
+ const a = gt(e);
916
+ await wt(`${this.folder}/stats.json`, a);
917
+ }
918
+ }
919
+ };
920
+ F.paths = [["export"]];
921
+ let U = F;
922
+ const C = new Q({
923
+ binaryName: "notion",
924
+ binaryLabel: lt,
925
+ binaryVersion: dt
926
+ });
927
+ C.register(U);
928
+ C.register(X.HelpCommand);
929
+ C.register(X.VersionCommand);
930
+ C.runExit(process.argv.slice(2), Q.defaultContext);
931
+ export {
932
+ U as NotionExportCommand,
933
+ ht as NotionExporter,
934
+ gt as computeStats,
935
+ ft as generateTreemaps,
936
+ A as getBlockLink,
937
+ Et as loadJson,
938
+ ut as loadRaw,
939
+ wt as writeStats
940
+ };
941
+ //# sourceMappingURL=main.js.map