crossnote 0.9.38 → 0.9.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Crossnote `[WIP]`
1
+ # Crossnote
2
2
 
3
3
  Also called as `mume` before.
4
4
 
package/out/cjs/index.cjs CHANGED
@@ -644,7 +644,7 @@ sidebarTOCBtn.addEventListener('click', function(event) {
644
644
  ${Ee}
645
645
  ${Mt}
646
646
  </html>
647
- `,k.embedLocalImages||k.embedSVG){let Xe=Hl.load(p);k.embedLocalImages&&await jk(Xe,this.notebook,this.resolveFilePath.bind(this)),k.embedSVG&&await bT(Xe,this.notebook,this.resolveFilePath.bind(this)),p=Xe.html()}return p.trim()}async openInBrowser({runAllCodeChunks:p=!1}={}){let w=await this.fs.readFile(this.filePath),k,S;({html:k,yamlConfig:S}=await this.parseMD(w,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:p})),k=await this.generateHTMLTemplateForExport(k,S,{isForPrint:!1,isForPrince:!1,offline:!0,embedLocalImages:!1,isForBrowser:!0});let I=await ts({prefix:"crossnote",suffix:".html"});Tn.writeFileSync(I.fd,k),qd(I.path)}async htmlExport({offline:p=!1,runAllCodeChunks:w=!1}={}){let k=this.filePath,S=Ke.extname(k);k=k.replace(new RegExp(S+"$"),".html");let I=await this.htmlExportDocument({offline:p,runAllCodeChunks:w});if(!p&&I.indexOf('[{"src":"revealjs_deps/notes.js","async":true}]')>=0){let N=Ke.resolve(Ke.dirname(k),"revealjs_deps");Tn.existsSync(N)||Tn.mkdirSync(N),Tn.createReadStream(Ke.resolve(Ct(),"./dependencies/reveal/plugin/notes/notes.js")).pipe(Tn.createWriteStream(Ke.resolve(N,"notes.js"))),Tn.createReadStream(Ke.resolve(Ct(),"./dependencies/reveal/plugin/notes/notes.html")).pipe(Tn.createWriteStream(Ke.resolve(N,"notes.html")))}return await this.fs.writeFile(k,I),k}async htmlExportDocument({offline:p=!1,embedLocalImages:w=!1,embedSVG:k=!0,runAllCodeChunks:S=!1}={}){let I=await this.fs.readFile(this.filePath),N,O;({html:N,yamlConfig:O}=await this.parseMD(I,{useRelativeFilePath:!0,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:S}));let B=O.html||{};return"offline"in B&&(p=B.offline),"embed_local_images"in B&&(w=!!B.embed_local_images),"embed_svg"in B&&(k=B.embed_svg),this.generateHTMLTemplateForExport(N,O,{isForPrint:!1,isForPrince:!1,embedLocalImages:w,offline:p,embedOfflineAssets:p,embedSVG:k})}async chromeExport({fileType:p="pdf",runAllCodeChunks:w=!1,openFileAfterGeneration:k=!1}={}){let S=await this.fs.readFile(this.filePath),I,N;({html:I,yamlConfig:N}=await this.parseMD(S,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:w}));let O=this.filePath,B=Ke.extname(O);O=O.replace(new RegExp(B+"$"),"."+p),I=await this.generateHTMLTemplateForExport(I,N,{isForPrint:!0,isForPrince:!1,embedLocalImages:!1,offline:!0});let H;try{if(H=this.notebook.config.chromePath,!H){let ye=(await import("chrome-paths")).default;H=ye.chrome||ye.chromeCanary||ye.chromium||""}}catch{H=""}if(!H)throw new Error("Chrome executable path is not set.");let K=await(await import("puppeteer-core/lib/cjs/puppeteer/puppeteer-core.js")).launch({args:this.notebook.config.puppeteerArgs||[],executablePath:H,headless:!0}),q=await ts({prefix:"crossnote",suffix:".html"});Tn.writeFileSync(q.fd,I);let ae=await K.newPage(),Y=Gl(q.path)+(N.isPresentationMode?"?print-pdf":"");await ae.goto(Y);let ee=N.chrome&&typeof N.chrome=="object"&&!Array.isArray(N.chrome)?N.chrome:void 0,ce=N.puppeteer&&typeof N.puppeteer=="object"&&!Array.isArray(N.puppeteer)?N.puppeteer:void 0,de={path:O,...N.isPresentationMode?{}:{margin:{top:"1cm",bottom:"1cm",left:"1cm",right:"1cm"}},printBackground:this.notebook.config.printBackground,...ee||ce||{}},se=0;return ee&&ee.timeout?se=ee.timeout:ce&&ce.timeout&&(se=ce.timeout),se&&typeof se=="number"?await new Promise(ye=>setTimeout(ye,se)):this.notebook.config.puppeteerWaitForTimeout&&this.notebook.config.puppeteerWaitForTimeout>0&&await new Promise(ye=>setTimeout(ye,this.notebook.config.puppeteerWaitForTimeout)),p==="pdf"?await ae.pdf(de):(de.fullPage=!0,await ae.screenshot(de)),K.close(),k&&qd(O),O}async princeExport({runAllCodeChunks:p=!1,openFileAfterGeneration:w=!1}={}){let k=await this.fs.readFile(this.filePath),S,I;({html:S,yamlConfig:I}=await this.parseMD(k,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:p}));let N=this.filePath,O=Ke.extname(N);N=N.replace(new RegExp(O+"$"),".pdf"),S=await this.generateHTMLTemplateForExport(S,I,{isForPrint:!0,isForPrince:!0,embedLocalImages:!1,offline:!0});let B=await ts({prefix:"crossnote",suffix:".html"});return Tn.writeFileSync(B.fd,S),I.isPresentationMode?Gl(B.path)+"?print-pdf":(await Y2(B.path,N),w&&qd(N),N)}async eBookDownloadImages(p,w){let k=[];(Ke.extname(w)===".epub"||Ke.extname("dest")===".mobi")&&p("img").each((I,N)=>{let O=p(N);(O.attr("src")||"").match(/^https?:\/\//)&&k.push(O)});let S=k.map(async I=>{let N=I.attr("src")??"",O=Math.random().toString(36).substr(2,9)+"_"+Ke.basename(N);O=Ke.resolve(this.fileDirectoryPath,O);let B=await fetch(N);if(!B.ok||!B.body)throw new Error(`Failed to download image from ${N}`);let{pipeline:H}=await import("stream/promises"),{Readable:V}=await import("stream");return await H(V.fromWeb(B.body),Tn.createWriteStream(O)),I.attr("src",Gl(O)),O});return Promise.all(S)}async eBookExport({fileType:p="epub",runAllCodeChunks:w=!1}){let k=await this.fs.readFile(this.filePath),S=p==="pdf",I,N;({html:I,yamlConfig:N}=await this.parseMD(k,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:w,emojiToSvg:S}));let O=this.filePath,B=Ke.extname(O);O=O.replace(new RegExp(B+"$"),"."+p.toLowerCase());let H=N.ebook||{};if(!H)throw new Error("eBook config not found. Please insert ebook front-matter to your markdown file.");if(H.cover){let pe=H.cover;H.cover=Us(this.resolveFilePath(pe,!1))}let V=Hl.load(`<div>${I}</div>`),K=[],q=new br,ae=V("div > ul").last();if(ae.length){if(H.include_toc===!1){let pe=ae.prev();pe.length&&pe[0].name.match(/^h\d$/i)&&pe.remove()}V("h1, h2, h3, h4, h5, h6").each((pe,he)=>{let Ue=V(he),Qe=parseInt(Ue[0].name.slice(1),10)-1;Ue.attr("ebook-toc-level-"+(Qe+1),""),Ue.attr("heading",Ue.html())}),Y(ae,0),H.include_toc===!1&&ae.remove()}function Y(pe,he){pe.children("li").each((Ue,Qe)=>{let at=V(Qe),$e=at.children("a").first();if(!$e.length){at.children().length>=1&&Y(at.children().last(),he+1);return}let Ie=decodeURIComponent($e.attr("href")??""),_e=$e.html()??"",Ne=q.generateId("ebook-heading-"+_e);K.push({level:he,filePath:Ie,heading:_e,id:Ne}),$e.attr("href","#"+Ne),at.children().length>1&&Y(at.children().last(),he+1)})}let ee=K.map(({heading:pe,id:he,level:Ue,filePath:Qe},at)=>new Promise(($e,Ie)=>{if(Qe=Us(Qe),Qe.match(/^https?:\/\//))return $e({heading:pe,id:he,level:Ue,filePath:Qe,html:"",offset:at});Tn.readFile(Qe,{encoding:"utf-8"},(_e,Ne)=>{if(_e)return Ie(_e.toString());let It=Ke.dirname(this.filePath);Ne=Ne.replace(/(!\[[^\]]*\]\()(\.[^)\s]*)/g,(Mt,En,Gt)=>{let Le=Ke.resolve(Ke.dirname(Qe),Gt),Xe=Ke.relative(It,Le);return En+Xe}),this.parseMD(Ne,{useRelativeFilePath:!1,isForPreview:!1,hideFrontMatter:!0,emojiToSvg:S,fileDirectoryPath:Ke.dirname(Qe)}).then(({html:Mt})=>$e({heading:pe,id:he,level:Ue,filePath:Qe,html:Mt,offset:at}))})})),ce=V.html().replace(/^<div>(.+)<\/div>$/,"$1"),de=await Promise.all(ee);de=de.sort((pe,he)=>pe.offset-he.offset),de.forEach(({heading:pe,id:he,level:Ue,html:Qe})=>{let at=Hl.load(`<div>${Qe}</div>`);at("a").each(($e,Ie)=>{let _e=at(Ie),Ne=_e.attr("href");Ne&&Ne.startsWith("file://")&&de.forEach(It=>{It.filePath===Us(Ne)&&_e.attr("href","#"+It.id)})}),ce+=`<div id="${he}" ebook-toc-level-${Ue+1} heading="${pe}">${at.html()}</div>`}),V=Hl.load(ce);let se=await this.eBookDownloadImages(V,O);if(Ke.extname(O)===".html"){if(H.cover){let pe=H.cover,he=pe[0]==="/"?Gl(pe):pe;V(":root").children().first().prepend(`<img style="display:block; margin-bottom: 24px;" src="${he}">`)}await jk(V,this.notebook,this.resolveFilePath.bind(this))}ce=V.html();let ye=H.title||"no title",Ee="";ce.indexOf('class="katex"')>0&&(Ke.extname(O)===".html"&&H.html&&H.html.cdn?Ee=`<link rel="stylesheet" href="https://${this.notebook.config.jsdelivrCdnHost}/npm/katex@0.16.47/dist/katex.min.css">`:Ee=`<link rel="stylesheet" href="${Gl(Ke.resolve(Ct(),"./dependencies/katex/katex.min.css"))}">`);let xe;try{xe=(await Promise.all([await this.fs.readFile(Ke.resolve(Ct(),"./styles/style-template.css")),await this.fs.readFile(Ke.resolve(Ct(),`./styles/prism_theme/${qn.resolveThemeForExport(qn.AutoPrismThemeMap[H.theme||this.notebook.config.previewTheme]??"default.css","codeBlock")}`)),await this.fs.readFile(Ke.resolve(Ct(),"./styles/twemoji.css")),await this.fs.readFile(Ke.resolve(Ct(),`./styles/preview_theme/${qn.resolveThemeForExport(H.theme||this.notebook.config.previewTheme,"preview")}`)),ce.indexOf("admonition")>0?await this.fs.readFile(Ke.resolve(Ct(),"./styles/markdown-it-admonition.css")):"",ce.indexOf("callout")>0?await this.fs.readFile(Ke.resolve(Ct(),"./styles/markdown-it-callout.css")):""])).join("")}catch{xe=""}let He="";try{He=this.notebook.config.globalCss}catch{}if(I=`
647
+ `,k.embedLocalImages||k.embedSVG){let Xe=Hl.load(p);k.embedLocalImages&&await jk(Xe,this.notebook,this.resolveFilePath.bind(this)),k.embedSVG&&await bT(Xe,this.notebook,this.resolveFilePath.bind(this)),p=Xe.html()}return p.trim()}async openInBrowser({runAllCodeChunks:p=!1}={}){let w=await this.fs.readFile(this.filePath),k,S;({html:k,yamlConfig:S}=await this.parseMD(w,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:p})),k=await this.generateHTMLTemplateForExport(k,S,{isForPrint:!1,isForPrince:!1,offline:!0,embedLocalImages:!1,isForBrowser:!0});let I=await ts({prefix:"crossnote",suffix:".html"});Tn.writeFileSync(I.fd,k),qd(I.path)}async htmlExport({offline:p=!1,runAllCodeChunks:w=!1}={}){let k=this.filePath,S=Ke.extname(k);k=k.replace(new RegExp(S+"$"),".html");let I=await this.htmlExportDocument({offline:p,runAllCodeChunks:w});if(!p&&I.indexOf('[{"src":"revealjs_deps/notes.js","async":true}]')>=0){let N=Ke.resolve(Ke.dirname(k),"revealjs_deps");Tn.existsSync(N)||Tn.mkdirSync(N),Tn.createReadStream(Ke.resolve(Ct(),"./dependencies/reveal/plugin/notes/notes.js")).pipe(Tn.createWriteStream(Ke.resolve(N,"notes.js"))),Tn.createReadStream(Ke.resolve(Ct(),"./dependencies/reveal/plugin/notes/notes.html")).pipe(Tn.createWriteStream(Ke.resolve(N,"notes.html")))}return await this.fs.writeFile(k,I),k}async htmlExportDocument({offline:p=!1,embedLocalImages:w=!1,embedSVG:k=!0,runAllCodeChunks:S=!1}={}){let I=await this.fs.readFile(this.filePath),N,O;({html:N,yamlConfig:O}=await this.parseMD(I,{useRelativeFilePath:!0,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:S}));let B=O.html||{};return"offline"in B&&(p=B.offline),"embed_local_images"in B&&(w=!!B.embed_local_images),"embed_svg"in B&&(k=B.embed_svg),this.generateHTMLTemplateForExport(N,O,{isForPrint:!1,isForPrince:!1,embedLocalImages:w,offline:p,embedOfflineAssets:p,embedSVG:k})}async chromeExport({fileType:p="pdf",runAllCodeChunks:w=!1,openFileAfterGeneration:k=!1}={}){let S=await this.fs.readFile(this.filePath),I,N;({html:I,yamlConfig:N}=await this.parseMD(S,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:w}));let O=this.filePath,B=Ke.extname(O);O=O.replace(new RegExp(B+"$"),"."+p),I=await this.generateHTMLTemplateForExport(I,N,{isForPrint:!0,isForPrince:!1,embedLocalImages:!1,offline:!0});let H;try{if(H=this.notebook.config.chromePath,!H){let ye=(await import("chrome-paths")).default;H=ye.chrome||ye.chromeCanary||ye.chromium||""}}catch{H=""}if(!H)throw new Error("Chrome executable path is not set.");let K=await(await import("puppeteer-core/lib/cjs/puppeteer/puppeteer-core.js")).launch({args:this.notebook.config.puppeteerArgs||[],executablePath:H,headless:!0}),q=await ts({prefix:"crossnote",suffix:".html"});Tn.writeFileSync(q.fd,I);let ae=await K.newPage(),Y=Gl(q.path)+(N.isPresentationMode?"?print-pdf":"");await ae.goto(Y);let ee=N.chrome&&typeof N.chrome=="object"&&!Array.isArray(N.chrome)?N.chrome:void 0,ce=N.puppeteer&&typeof N.puppeteer=="object"&&!Array.isArray(N.puppeteer)?N.puppeteer:void 0,de={path:O,...N.isPresentationMode?{}:{margin:{top:"1cm",bottom:"1cm",left:"1cm",right:"1cm"}},printBackground:this.notebook.config.printBackground,...ee||ce||{}},se=0;return ee&&ee.timeout?se=ee.timeout:ce&&ce.timeout&&(se=ce.timeout),se&&typeof se=="number"?await new Promise(ye=>setTimeout(ye,se)):this.notebook.config.puppeteerWaitForTimeout&&this.notebook.config.puppeteerWaitForTimeout>0&&await new Promise(ye=>setTimeout(ye,this.notebook.config.puppeteerWaitForTimeout)),p==="pdf"?await ae.pdf(de):(de.fullPage=!0,await ae.screenshot(de)),K.close().catch(()=>{}),k&&qd(O),O}async princeExport({runAllCodeChunks:p=!1,openFileAfterGeneration:w=!1}={}){let k=await this.fs.readFile(this.filePath),S,I;({html:S,yamlConfig:I}=await this.parseMD(k,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:p}));let N=this.filePath,O=Ke.extname(N);N=N.replace(new RegExp(O+"$"),".pdf"),S=await this.generateHTMLTemplateForExport(S,I,{isForPrint:!0,isForPrince:!0,embedLocalImages:!1,offline:!0});let B=await ts({prefix:"crossnote",suffix:".html"});return Tn.writeFileSync(B.fd,S),I.isPresentationMode?Gl(B.path)+"?print-pdf":(await Y2(B.path,N),w&&qd(N),N)}async eBookDownloadImages(p,w){let k=[];(Ke.extname(w)===".epub"||Ke.extname("dest")===".mobi")&&p("img").each((I,N)=>{let O=p(N);(O.attr("src")||"").match(/^https?:\/\//)&&k.push(O)});let S=k.map(async I=>{let N=I.attr("src")??"",O=Math.random().toString(36).substr(2,9)+"_"+Ke.basename(N);O=Ke.resolve(this.fileDirectoryPath,O);let B=await fetch(N);if(!B.ok||!B.body)throw new Error(`Failed to download image from ${N}`);let{pipeline:H}=await import("stream/promises"),{Readable:V}=await import("stream");return await H(V.fromWeb(B.body),Tn.createWriteStream(O)),I.attr("src",Gl(O)),O});return Promise.all(S)}async eBookExport({fileType:p="epub",runAllCodeChunks:w=!1}){let k=await this.fs.readFile(this.filePath),S=p==="pdf",I,N;({html:I,yamlConfig:N}=await this.parseMD(k,{useRelativeFilePath:!1,hideFrontMatter:!0,isForPreview:!1,runAllCodeChunks:w,emojiToSvg:S}));let O=this.filePath,B=Ke.extname(O);O=O.replace(new RegExp(B+"$"),"."+p.toLowerCase());let H=N.ebook||{};if(!H)throw new Error("eBook config not found. Please insert ebook front-matter to your markdown file.");if(H.cover){let pe=H.cover;H.cover=Us(this.resolveFilePath(pe,!1))}let V=Hl.load(`<div>${I}</div>`),K=[],q=new br,ae=V("div > ul").last();if(ae.length){if(H.include_toc===!1){let pe=ae.prev();pe.length&&pe[0].name.match(/^h\d$/i)&&pe.remove()}V("h1, h2, h3, h4, h5, h6").each((pe,he)=>{let Ue=V(he),Qe=parseInt(Ue[0].name.slice(1),10)-1;Ue.attr("ebook-toc-level-"+(Qe+1),""),Ue.attr("heading",Ue.html())}),Y(ae,0),H.include_toc===!1&&ae.remove()}function Y(pe,he){pe.children("li").each((Ue,Qe)=>{let at=V(Qe),$e=at.children("a").first();if(!$e.length){at.children().length>=1&&Y(at.children().last(),he+1);return}let Ie=decodeURIComponent($e.attr("href")??""),_e=$e.html()??"",Ne=q.generateId("ebook-heading-"+_e);K.push({level:he,filePath:Ie,heading:_e,id:Ne}),$e.attr("href","#"+Ne),at.children().length>1&&Y(at.children().last(),he+1)})}let ee=K.map(({heading:pe,id:he,level:Ue,filePath:Qe},at)=>new Promise(($e,Ie)=>{if(Qe=Us(Qe),Qe.match(/^https?:\/\//))return $e({heading:pe,id:he,level:Ue,filePath:Qe,html:"",offset:at});Tn.readFile(Qe,{encoding:"utf-8"},(_e,Ne)=>{if(_e)return Ie(_e.toString());let It=Ke.dirname(this.filePath);Ne=Ne.replace(/(!\[[^\]]*\]\()(\.[^)\s]*)/g,(Mt,En,Gt)=>{let Le=Ke.resolve(Ke.dirname(Qe),Gt),Xe=Ke.relative(It,Le);return En+Xe}),this.parseMD(Ne,{useRelativeFilePath:!1,isForPreview:!1,hideFrontMatter:!0,emojiToSvg:S,fileDirectoryPath:Ke.dirname(Qe)}).then(({html:Mt})=>$e({heading:pe,id:he,level:Ue,filePath:Qe,html:Mt,offset:at}))})})),ce=V.html().replace(/^<div>(.+)<\/div>$/,"$1"),de=await Promise.all(ee);de=de.sort((pe,he)=>pe.offset-he.offset),de.forEach(({heading:pe,id:he,level:Ue,html:Qe})=>{let at=Hl.load(`<div>${Qe}</div>`);at("a").each(($e,Ie)=>{let _e=at(Ie),Ne=_e.attr("href");Ne&&Ne.startsWith("file://")&&de.forEach(It=>{It.filePath===Us(Ne)&&_e.attr("href","#"+It.id)})}),ce+=`<div id="${he}" ebook-toc-level-${Ue+1} heading="${pe}">${at.html()}</div>`}),V=Hl.load(ce);let se=await this.eBookDownloadImages(V,O);if(Ke.extname(O)===".html"){if(H.cover){let pe=H.cover,he=pe[0]==="/"?Gl(pe):pe;V(":root").children().first().prepend(`<img style="display:block; margin-bottom: 24px;" src="${he}">`)}await jk(V,this.notebook,this.resolveFilePath.bind(this))}ce=V.html();let ye=H.title||"no title",Ee="";ce.indexOf('class="katex"')>0&&(Ke.extname(O)===".html"&&H.html&&H.html.cdn?Ee=`<link rel="stylesheet" href="https://${this.notebook.config.jsdelivrCdnHost}/npm/katex@0.16.47/dist/katex.min.css">`:Ee=`<link rel="stylesheet" href="${Gl(Ke.resolve(Ct(),"./dependencies/katex/katex.min.css"))}">`);let xe;try{xe=(await Promise.all([await this.fs.readFile(Ke.resolve(Ct(),"./styles/style-template.css")),await this.fs.readFile(Ke.resolve(Ct(),`./styles/prism_theme/${qn.resolveThemeForExport(qn.AutoPrismThemeMap[H.theme||this.notebook.config.previewTheme]??"default.css","codeBlock")}`)),await this.fs.readFile(Ke.resolve(Ct(),"./styles/twemoji.css")),await this.fs.readFile(Ke.resolve(Ct(),`./styles/preview_theme/${qn.resolveThemeForExport(H.theme||this.notebook.config.previewTheme,"preview")}`)),ce.indexOf("admonition")>0?await this.fs.readFile(Ke.resolve(Ct(),"./styles/markdown-it-admonition.css")):"",ce.indexOf("callout")>0?await this.fs.readFile(Ke.resolve(Ct(),"./styles/markdown-it-callout.css")):""])).join("")}catch{xe=""}let He="";try{He=this.notebook.config.globalCss}catch{}if(I=`
648
648
  <!DOCTYPE html>
649
649
  <html>
650
650
  <head>
@@ -717,15 +717,6 @@ ${w}
717
717
  };
718
718
  return api;
719
719
  };
720
- // The shell tells the frames when zen mode is on: Esc must then exit zen
721
- // (the welcome card and the exit button both promise that), instead of the
722
- // preview's own Esc behavior of toggling the sidebar TOC.
723
- var zenMode = false;
724
- window.addEventListener('message', function (event) {
725
- if (event.data && event.data.command === '__serverAppZenMode') {
726
- zenMode = !!event.data.enabled;
727
- }
728
- });
729
720
  document.addEventListener('keydown', function (event) {
730
721
  var key = event.key.toLowerCase();
731
722
  var action = null;
@@ -735,8 +726,6 @@ ${w}
735
726
  action = 'split-pane';
736
727
  } else if (event.altKey && key === 'w') {
737
728
  action = 'close-tab';
738
- } else if (key === 'escape' && zenMode) {
739
- action = 'exit-zen-mode';
740
729
  }
741
730
  if (action) {
742
731
  event.preventDefault();
@@ -748,17 +737,17 @@ ${w}
748
737
  }, true);
749
738
  })();
750
739
  </script>`}var Kk=ze(require("fs")),IT=ze(require("os")),uu=ze(require("path"));var zy=ze(require("fs")),_F=ze(require("os")),Hs=ze(require("path")),xF=ze(require("json5"));var kF="markdown-preview-enhanced.";function SF(d){if(d)return Hs.resolve(d);let p=_F.homedir(),w=process.platform==="win32"?[Hs.join(p,"AppData/Roaming/Code - Insiders/User/settings.json"),Hs.join(p,"AppData/Roaming/Code/User/settings.json")]:process.platform==="darwin"?[Hs.join(p,"Library/Application Support/Code - Insiders/User/settings.json"),Hs.join(p,"Library/Application Support/Code/User/settings.json")]:[Hs.join(p,".config/Code - Insiders/User/settings.json"),Hs.join(p,".config/Code/User/settings.json")];for(let k of w)if(zy.existsSync(k))return k;return null}async function AF(d){if(!d||!zy.existsSync(d))return null;let p=await zy.promises.readFile(d,"utf-8"),w;try{w=xF.default.parse(p)}catch(S){return console.error(`crossnote serve: failed to parse VS Code settings at ${d}:`,S),null}let k={};for(let[S,I]of Object.entries(w))S.startsWith(kF)&&(k[S.slice(kF.length)]=I);return k}function Uj(){return process.platform==="win32"?uu.join(IT.homedir(),"./.crossnote"):typeof process.env.XDG_CONFIG_HOME=="string"&&process.env.XDG_CONFIG_HOME!==""?uu.resolve(process.env.XDG_CONFIG_HOME,"./crossnote"):uu.resolve(IT.homedir(),"./.local/state/crossnote")}async function zj(d){let p=d.globalConfigDirectory??Uj();return{rootDirectory:uu.resolve(d.rootDirectory),vscode:!!d.vscode,globalConfigDirectory:p,vscodeSettingsPath:d.vscode?SF(d.vscodeSettingsPath):null}}async function Gj(d){let p=null;d.vscode&&(p=await AF(d.vscodeSettingsPath));let w={};try{w=await ou(d.globalConfigDirectory,su(),!0)}catch(N){console.error("Failed to load global crossnote config:",N)}let k={},S=uu.join(d.rootDirectory,"./.crossnote");try{Kk.existsSync(S)&&(k=await ou(S,su(),!1))}catch(N){console.error("Failed to load workspace config:",N)}let I={...p??{},...w,...k,globalCss:(w.globalCss??"")+(k.globalCss??"")};return p!=null&&p.previewTheme&&(I.previewTheme=p.previewTheme),I}async function TF(d,p={}){let w=[];for(let I of d){let N=uu.resolve(I),O=await Kk.promises.stat(N).catch(()=>null);if(!(O!=null&&O.isDirectory()))throw new Error(`Not a directory: ${N}`);w.includes(N)||w.push(N)}let k=await Promise.all(w.map(I=>zj({rootDirectory:I,vscode:p.vscode,vscodeSettingsPath:p.vscodeSettingsPath,globalConfigDirectory:p.globalConfigDirectory}))),S=await Promise.all(k.map(async I=>$y.init({notebookPath:I.rootDirectory,config:await Gj(I)})));return{rootDirectories:w,configContexts:k,notebooks:S}}var tf=ze(require("fs")),ql=ze(require("path")),CF=ze(require("ignore")),jj=[".md",".markdown",".mdx"],Hj=new Set(["node_modules",".git"]);function qj(d){return jj.includes(ql.extname(d).toLowerCase())}function Xk(d,p){return Wj(process.platform,d,p)}function Wj(d,p,w){if(d==="win32"){let S=p.toLowerCase(),I=w.toLowerCase();return I===S||I.startsWith(S+"\\")}return w===p||w.startsWith(p+"/")}async function RF(d,p=5e3){let w=ql.join(d,".gitignore"),k=()=>!1;try{if(tf.existsSync(w)){let N=(0,CF.default)();N.add(tf.readFileSync(w,"utf-8")),k=O=>N.ignores(O)}}catch{}let S=[],I=[d];for(;I.length>0&&S.length<p;){let N=I.shift(),O;try{O=await tf.promises.readdir(N,{withFileTypes:!0})}catch{continue}for(let B of O){let H=ql.join(N,B.name),V=ql.relative(d,H).split(ql.sep).join("/");if(!(k(V)||B.isDirectory()&&k(`${V}/`))){if(B.isDirectory()){if(B.name.startsWith(".")||Hj.has(B.name))continue;I.push(H)}else if(B.isFile()&&qj(B.name))try{let K=await tf.promises.stat(H);S.push({relativePath:V,absolutePath:H,mtimeMs:K.mtimeMs})}catch{}}}}return S.sort((N,O)=>N.relativePath.localeCompare(O.relativePath))}var Vj="crossnote-wiki-asset:",NT="crossnote-wiki-theme:",Yj=EF("'*'"),MT={avif:"image/avif",bmp:"image/bmp",gif:"image/gif",ico:"image/x-icon",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp"},Kj=new Set([".js",".mjs",".cjs",".css"]);function Xj(d){return Zt.extname(d).toLowerCase().slice(1)in MT}function OT(d){return d.split(Zt.sep).join("/")}async function DF(d){var He;let p=Zt.resolve(d.crossnoteBuildDirectory??Ct());pk(p);let{rootDirectories:w,notebooks:k}=await TF(d.directories,{vscode:d.vscode,vscodeSettingsPath:d.vscodeSettingsPath,globalConfigDirectory:d.globalConfigDirectory}),S=w.length>1,I=w.map(be=>Zt.basename(be)||be),N=(be,pe)=>{let he=OT(Zt.relative(w[pe],be));return S?`${I[pe]}/${he}`:he},O=new Map,B=0,H=be=>{let pe=Zt.resolve(be),he=O.get(pe);return he===void 0&&(he=String(B++),O.set(pe,he)),`${Vj}${he}`},V=be=>{let pe=Zt.extname(be).toLowerCase().slice(1),he=MT[pe];if(!he)return null;let Ue=K(be),Qe=[Ue];try{let at=decodeURIComponent(Ue);at!==Ue&&Qe.push(at)}catch{}for(let at of Qe)try{let $e=mo.readFileSync(at).toString("base64");return`data:${he};base64,${$e}`}catch{}return null};function K(be){return be.replace(/\?.+$/,"")}let q={},ae=hk(be=>{let pe=K(be);if(Xk(p,pe)){let he=OT(Zt.relative(p,pe));return he.startsWith("styles/preview_theme/")?`${NT}preview`:he.startsWith("styles/prism_theme/")?`${NT}codeBlock`:he.startsWith("dependencies/reveal/css/theme/")?`${NT}reveal`:H(pe)}for(let he of w){if(!Xk(he,pe))continue;if(Xj(pe)){let Qe=V(pe);return Qe||tn(pe)}if(Kj.has(Zt.extname(pe).toLowerCase()))return H(pe);let Ue=Zt.relative(he,pe);return`/${OT(Ue)}`}return tn(pe)}),Y=[],ee=[],ce=new Map;try{for(let be=0;be<w.length;be++){let pe=w[be],he=k[be],Ue=await RF(pe),Qe=0;for(let at of Ue){try{let $e=await mo.promises.readFile(at.absolutePath,"utf-8"),Ie=he.getNoteMarkdownEngine(at.absolutePath),_e=await Ie.parseMD($e,{isForPreview:!0,useRelativeFilePath:!1,hideFrontMatter:!1,vscodePreviewPanel:q});_e.html=await e5(_e.html,ce);let Ne=N(at.absolutePath,be),It=await Ie.generateHTMLTemplateForPreview({inputString:$e,parsedOutput:_e,vscodePreviewPanel:q,config:{sourceUri:Ne,isVSCode:!1,isServerApp:!0,isWiki:!0},scripts:Yj,head:""}),Mt=_e.yamlConfig,En=typeof Mt.title=="string"&&Mt.title.trim()||Zt.basename(at.absolutePath,Zt.extname(at.absolutePath)),Gt=(await mo.promises.stat(at.absolutePath)).mtimeMs;Y.push({path:Ne,root:I[be],title:En,mtimeMs:Gt,html:It,update:{markdown:$e,html:_e.html,tocHTML:_e.tocHTML,totalLineCount:$e.split(`
751
- `).length,sourceUri:Ne,sourceScheme:"file",id:Mt.id||"",class:Mt.class||"",jsAndCssFiles:_e.JSAndCssFiles}})}catch($e){ee.push({path:at.absolutePath,error:String($e)})}Qe+=1,(He=d.onProgress)==null||He.call(d,{rendered:Qe,total:Ue.length,root:pe})}}}finally{ae()}if(Y.length===0)throw new Error("no markdown notes found to build a wiki from"+(ee.length>0?` (${ee.length} notes failed to render)`:""));let de={};for(let[be,pe]of O)de[pe]=Zt.extname(be).toLowerCase()===".css"?await DT(be):await mo.promises.readFile(be,"utf-8").catch(()=>"");de["graph-view.js"]=await mo.promises.readFile(Zt.join(p,"webview","graph-view.js"),"utf-8").catch(()=>""),de["graph-view.css"]=await DT(Zt.join(p,"webview","graph-view.css")).catch(()=>"");let se=await Jj(p,k[0]),ye={},Ee={};for(let be=0;be<w.length;be++){let pe=k[be];try{await pe.refreshNotesIfNotLoaded({dir:".",includeSubdirectories:!0}),ye[I[be]]=Uk(pe)}catch(he){console.error(`crossnote build-wiki: failed to build graph data for ${w[be]}:`,he)}for(let he of Y)if(he.root===I[be])try{Ee[he.path]=(await pe.getNoteBacklinks(Zt.join(w[be],...he.path.split("/")))??[]).map(Ue=>Zj(Ue,w[be]))}catch{Ee[he.path]=[]}}return{html:n5({rootNames:I,files:Y,assets:de,themes:se,graph:ye,backlinks:Ee,buildDirectory:p}),files:Y.map(({path:be,root:pe,title:he,mtimeMs:Ue})=>({path:be,root:pe,title:he,mtimeMs:Ue})),rootDirectories:w,failures:ee}}function Zj(d,p){var w,k,S;return{note:{notebookPath:{scheme:"file",path:"/"},filePath:(((w=d.note)==null?void 0:w.filePath)??"").replace(/\\/g,"/"),title:((k=d.note)==null?void 0:k.title)??"",config:(S=d.note)==null?void 0:S.config},references:(d.references??[]).map(I=>({...I,html:typeof I.html=="string"?IF(I.html,p):I.html})),referenceHtmls:(d.referenceHtmls??[]).map(I=>IF(I,p))}}function IF(d,p){try{let w=OF.load(d);return w("a[href], img[src]").each((k,S)=>{for(let I of["href","src"]){let N=w(S).attr(I);if(!N)continue;let O=N;try{O=decodeURIComponent(N)}catch{}let B=O.match(/^file:\/\/\/+(.*)$/i);B&&(O=B[1],/^[A-Za-z]:/.test(O)||(O="/"+O));let H=O.replace(/\//g,Zt.sep);if(!Xk(p,H))continue;let V=Zt.relative(p,H).split(Zt.sep).join("/");w(S).attr(I,`file:///${V}`)}}),w.html()}catch{return d}}async function Jj(d,p){let w=async k=>{let S=Zt.join(d,...k.split("/")),I=await mo.promises.readdir(S).catch(()=>[]),N={};for(let O of I)O.toLowerCase().endsWith(".css")&&(N[O]=await DT(Zt.join(S,O)));return N};return{preview:await w("styles/preview_theme"),codeBlock:await w("styles/prism_theme"),reveal:await w("dependencies/reveal/css/theme"),codeBlockAuto:{...Qd.AutoPrismThemeMap},build:{preview:p.config.previewTheme,codeBlock:p.config.codeBlockTheme,reveal:p.config.revealjsTheme}}}var Qj=1e4,NF=8*1024*1024;async function e5(d,p){let w=new Set;for(let S of d.matchAll(/<img[^>]*\ssrc="(https?:[^"]+)"/g))w.add(S[1]);if(w.size===0)return d;let k=new Map;return await Promise.all(Array.from(w).map(async S=>{let I=p.get(S);I===void 0&&(I=await t5(S),p.set(S,I)),I&&k.set(S,I)})),k.size===0?d:d.replace(/(<img[^>]*\ssrc=")(https?:[^"]+)(")/g,(S,I,N,O)=>k.has(N)?`${I}${k.get(N)}${O}`:S)}async function t5(d){try{let p=await fetch(d,{signal:AbortSignal.timeout(Qj),redirect:"follow"});if(!p.ok)return null;let w=parseInt(p.headers.get("content-length")??"",10);if(Number.isInteger(w)&&w>NF)return null;let k=Buffer.from(await p.arrayBuffer());if(k.length===0||k.length>NF)return null;let S=(p.headers.get("content-type")??"").split(";")[0];return S.startsWith("image/")?`data:${S};base64,${k.toString("base64")}`:null}catch{return null}}async function DT(d){let p;try{p=await mo.promises.readFile(d,"utf-8")}catch{return""}let w=Zt.dirname(d),k=new Map;return p.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(S,I,N)=>{if(N.startsWith("data:")||N.startsWith("#")||/^[a-z][a-z0-9+.-]*:/i.test(N)||N.startsWith("//"))return S;let O=k.get(N);if(O===void 0){O="";try{let B=Zt.resolve(w,decodeURIComponent(N)),H=Zt.extname(B).toLowerCase().slice(1),V=MT[H]??(H==="woff2"?"font/woff2":H==="woff"?"font/woff":H==="ttf"?"font/ttf":H==="otf"?"font/otf":H==="eot"?"application/vnd.ms-fontobject":"application/octet-stream"),K=mo.readFileSync(B).toString("base64");O=`data:${V};base64,${K}`}catch{}k.set(N,O)}return O?`url("${O}")`:S})}function n5({rootNames:d,files:p,assets:w,themes:k,graph:S,backlinks:I,buildDirectory:N}){let O=Zt.join(N,"server-app","server-app.js"),B=Zt.join(N,"server-app","server-app.css"),H,V;try{H=mo.readFileSync(O,"utf-8"),V=mo.readFileSync(B,"utf-8")}catch(ee){throw new Error(`the server app bundle is missing (looked at ${O}); rebuild crossnote so out/server-app/ exists`,{cause:ee})}let K=JSON.stringify({rootDirectories:d,assets:w,themes:k,graph:S,backlinks:I,files:p}).replace(/</g,"\\u003c"),q=H.replace(/<\/script/g,"<\\/script"),ae=V.replace(/<\/style/g,"<\\/style"),Y=`wiki \u2014 ${d[0]??""}`;return`<!DOCTYPE html>
740
+ `).length,sourceUri:Ne,sourceScheme:"file",id:Mt.id||"",class:Mt.class||"",jsAndCssFiles:_e.JSAndCssFiles}})}catch($e){ee.push({path:at.absolutePath,error:String($e)})}Qe+=1,(He=d.onProgress)==null||He.call(d,{rendered:Qe,total:Ue.length,root:pe})}}}finally{ae()}if(Y.length===0)throw new Error("no markdown notes found to build a wiki from"+(ee.length>0?` (${ee.length} notes failed to render)`:""));let de={};for(let[be,pe]of O)de[pe]=Zt.extname(be).toLowerCase()===".css"?await DT(be):await mo.promises.readFile(be,"utf-8").catch(()=>"");de["graph-view.js"]=await mo.promises.readFile(Zt.join(p,"webview","graph-view.js"),"utf-8").catch(()=>""),de["graph-view.css"]=await DT(Zt.join(p,"webview","graph-view.css")).catch(()=>"");let se=await Jj(p,k[0]),ye={},Ee={};for(let be=0;be<w.length;be++){let pe=k[be];try{await pe.refreshNotesIfNotLoaded({dir:".",includeSubdirectories:!0}),ye[I[be]]=Uk(pe)}catch(he){console.error(`crossnote build-wiki: failed to build graph data for ${w[be]}:`,he)}for(let he of Y)if(he.root===I[be])try{Ee[he.path]=(await pe.getNoteBacklinks(Zt.join(w[be],...he.path.split("/")))??[]).map(Ue=>Zj(Ue,w[be]))}catch{Ee[he.path]=[]}}return{html:n5({rootNames:I,files:Y,assets:de,themes:se,zenEnabled:k[0].config.enablePreviewZenMode,graph:ye,backlinks:Ee,buildDirectory:p}),files:Y.map(({path:be,root:pe,title:he,mtimeMs:Ue})=>({path:be,root:pe,title:he,mtimeMs:Ue})),rootDirectories:w,failures:ee}}function Zj(d,p){var w,k,S;return{note:{notebookPath:{scheme:"file",path:"/"},filePath:(((w=d.note)==null?void 0:w.filePath)??"").replace(/\\/g,"/"),title:((k=d.note)==null?void 0:k.title)??"",config:(S=d.note)==null?void 0:S.config},references:(d.references??[]).map(I=>({...I,html:typeof I.html=="string"?IF(I.html,p):I.html})),referenceHtmls:(d.referenceHtmls??[]).map(I=>IF(I,p))}}function IF(d,p){try{let w=OF.load(d);return w("a[href], img[src]").each((k,S)=>{for(let I of["href","src"]){let N=w(S).attr(I);if(!N)continue;let O=N;try{O=decodeURIComponent(N)}catch{}let B=O.match(/^file:\/\/\/+(.*)$/i);B&&(O=B[1],/^[A-Za-z]:/.test(O)||(O="/"+O));let H=O.replace(/\//g,Zt.sep);if(!Xk(p,H))continue;let V=Zt.relative(p,H).split(Zt.sep).join("/");w(S).attr(I,`file:///${V}`)}}),w.html()}catch{return d}}async function Jj(d,p){let w=async k=>{let S=Zt.join(d,...k.split("/")),I=await mo.promises.readdir(S).catch(()=>[]),N={};for(let O of I)O.toLowerCase().endsWith(".css")&&(N[O]=await DT(Zt.join(S,O)));return N};return{preview:await w("styles/preview_theme"),codeBlock:await w("styles/prism_theme"),reveal:await w("dependencies/reveal/css/theme"),codeBlockAuto:{...Qd.AutoPrismThemeMap},build:{preview:p.config.previewTheme,codeBlock:p.config.codeBlockTheme,reveal:p.config.revealjsTheme}}}var Qj=1e4,NF=8*1024*1024;async function e5(d,p){let w=new Set;for(let S of d.matchAll(/<img[^>]*\ssrc="(https?:[^"]+)"/g))w.add(S[1]);if(w.size===0)return d;let k=new Map;return await Promise.all(Array.from(w).map(async S=>{let I=p.get(S);I===void 0&&(I=await t5(S),p.set(S,I)),I&&k.set(S,I)})),k.size===0?d:d.replace(/(<img[^>]*\ssrc=")(https?:[^"]+)(")/g,(S,I,N,O)=>k.has(N)?`${I}${k.get(N)}${O}`:S)}async function t5(d){try{let p=await fetch(d,{signal:AbortSignal.timeout(Qj),redirect:"follow"});if(!p.ok)return null;let w=parseInt(p.headers.get("content-length")??"",10);if(Number.isInteger(w)&&w>NF)return null;let k=Buffer.from(await p.arrayBuffer());if(k.length===0||k.length>NF)return null;let S=(p.headers.get("content-type")??"").split(";")[0];return S.startsWith("image/")?`data:${S};base64,${k.toString("base64")}`:null}catch{return null}}async function DT(d){let p;try{p=await mo.promises.readFile(d,"utf-8")}catch{return""}let w=Zt.dirname(d),k=new Map;return p.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(S,I,N)=>{if(N.startsWith("data:")||N.startsWith("#")||/^[a-z][a-z0-9+.-]*:/i.test(N)||N.startsWith("//"))return S;let O=k.get(N);if(O===void 0){O="";try{let B=Zt.resolve(w,decodeURIComponent(N)),H=Zt.extname(B).toLowerCase().slice(1),V=MT[H]??(H==="woff2"?"font/woff2":H==="woff"?"font/woff":H==="ttf"?"font/ttf":H==="otf"?"font/otf":H==="eot"?"application/vnd.ms-fontobject":"application/octet-stream"),K=mo.readFileSync(B).toString("base64");O=`data:${V};base64,${K}`}catch{}k.set(N,O)}return O?`url("${O}")`:S})}function n5({rootNames:d,files:p,assets:w,themes:k,zenEnabled:S,graph:I,backlinks:N,buildDirectory:O}){let B=Zt.join(O,"server-app","server-app.js"),H=Zt.join(O,"server-app","server-app.css"),V,K;try{V=mo.readFileSync(B,"utf-8"),K=mo.readFileSync(H,"utf-8")}catch(ce){throw new Error(`the server app bundle is missing (looked at ${B}); rebuild crossnote so out/server-app/ exists`,{cause:ce})}let q=JSON.stringify({rootDirectories:d,assets:w,themes:k,zenEnabled:S,graph:I,backlinks:N,files:p}).replace(/</g,"\\u003c"),ae=V.replace(/<\/script/g,"<\\/script"),Y=K.replace(/<\/style/g,"<\\/style"),ee=`wiki \u2014 ${d[0]??""}`;return`<!DOCTYPE html>
752
741
  <html>
753
742
  <head>
754
743
  <meta charset="UTF-8">
755
744
  <meta name="viewport" content="width=device-width, initial-scale=1">
756
- <title>${r5(Y)}</title>
757
- <style>${ae}</style>
745
+ <title>${r5(ee)}</title>
746
+ <style>${Y}</style>
758
747
  </head>
759
748
  <body>
760
- <script>window.__CROSSNOTE_WIKI__ = ${K};</script>
749
+ <script>window.__CROSSNOTE_WIKI__ = ${q};</script>
761
750
  <div id="root"></div>
762
- <script>${q}</script>
751
+ <script>${ae}</script>
763
752
  </body>
764
753
  </html>`}function r5(d){return d.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var a5={addFileProtocol:tn,getCrossnoteBuildDirectory:Ct,openFile:qd,setCrossnoteBuildDirectory:pk,useExternalAddFileProtocolFunction:hk,uploadImage:WA};0&&(module.exports={HeadingIdGenerator,IS_NODE,MarkdownEngine,Notebook,PreviewMode,ReferenceMap,TagReferenceMap,buildWiki,constructGraphView,extractBlockIds,extractHeadings,findFragmentTargetLine,getDefaultKatexConfig,getDefaultMathjaxConfig,getDefaultMermaidConfig,getDefaultNotebookConfig,getDefaultParserConfig,loadConfigsInDirectory,matter,matterStringify,transformMarkdown,utility,wrapNodeFSAsApi});
package/out/cli/index.cjs CHANGED
@@ -36244,7 +36244,8 @@ sidebarTOCBtn.addEventListener('click', function(event) {
36244
36244
  puppeteerConfig["fullPage"] = true;
36245
36245
  await page.screenshot(puppeteerConfig);
36246
36246
  }
36247
- browser.close();
36247
+ browser.close().catch(() => {
36248
+ });
36248
36249
  if (openFileAfterGeneration) {
36249
36250
  openFile(dest);
36250
36251
  }
@@ -37438,15 +37439,6 @@ function previewHostShimScript(targetOriginExpression) {
37438
37439
  };
37439
37440
  return api;
37440
37441
  };
37441
- // The shell tells the frames when zen mode is on: Esc must then exit zen
37442
- // (the welcome card and the exit button both promise that), instead of the
37443
- // preview's own Esc behavior of toggling the sidebar TOC.
37444
- var zenMode = false;
37445
- window.addEventListener('message', function (event) {
37446
- if (event.data && event.data.command === '__serverAppZenMode') {
37447
- zenMode = !!event.data.enabled;
37448
- }
37449
- });
37450
37442
  document.addEventListener('keydown', function (event) {
37451
37443
  var key = event.key.toLowerCase();
37452
37444
  var action = null;
@@ -37456,8 +37448,6 @@ function previewHostShimScript(targetOriginExpression) {
37456
37448
  action = 'split-pane';
37457
37449
  } else if (event.altKey && key === 'w') {
37458
37450
  action = 'close-tab';
37459
- } else if (key === 'escape' && zenMode) {
37460
- action = 'exit-zen-mode';
37461
37451
  }
37462
37452
  if (action) {
37463
37453
  event.preventDefault();
@@ -37565,13 +37555,37 @@ async function updateVSCodeSetting(settingsPath, key, value) {
37565
37555
  `;
37566
37556
  } else {
37567
37557
  const head = trimmed.slice(0, lastBrace).replace(/\s+$/, "");
37568
- const needsComma = head.length > 0 && !head.endsWith("{");
37569
- text = head + (needsComma ? "," : "") + `
37558
+ const candidates = [",", "\n,", ""];
37559
+ const insertions = candidates.map(
37560
+ (separator) => head + separator + `
37570
37561
  "${MPE_SETTINGS_PREFIX}${key}": ${serialized}
37571
37562
  }
37572
- `;
37563
+ `
37564
+ );
37565
+ const valid = insertions.find((candidate) => {
37566
+ try {
37567
+ import_json53.default.parse(candidate);
37568
+ return true;
37569
+ } catch {
37570
+ return false;
37571
+ }
37572
+ });
37573
+ if (!valid) {
37574
+ throw new Error(
37575
+ `cannot insert "${MPE_SETTINGS_PREFIX}${key}" into ${settingsPath} while keeping it parseable`
37576
+ );
37577
+ }
37578
+ text = valid;
37573
37579
  }
37574
37580
  }
37581
+ try {
37582
+ import_json53.default.parse(text);
37583
+ } catch (error) {
37584
+ throw new Error(
37585
+ `refusing to write settings.json that no longer parses (${settingsPath}): ${error}`,
37586
+ { cause: error }
37587
+ );
37588
+ }
37575
37589
  await fs15.promises.mkdir(path19.dirname(settingsPath), { recursive: true });
37576
37590
  await fs15.promises.writeFile(settingsPath, text, "utf-8");
37577
37591
  }
@@ -38036,6 +38050,9 @@ async function buildWiki(options) {
38036
38050
  files,
38037
38051
  assets,
38038
38052
  themes,
38053
+ // The zen state the notes were built with — the baseline the
38054
+ // context-menu toggle flips (first root anchors, like the themes).
38055
+ zenEnabled: notebooks[0].config.enablePreviewZenMode,
38039
38056
  graph,
38040
38057
  backlinks,
38041
38058
  buildDirectory
@@ -38230,6 +38247,7 @@ function buildShellHTML({
38230
38247
  files,
38231
38248
  assets,
38232
38249
  themes,
38250
+ zenEnabled,
38233
38251
  graph,
38234
38252
  backlinks,
38235
38253
  buildDirectory
@@ -38259,6 +38277,7 @@ function buildShellHTML({
38259
38277
  rootDirectories: rootNames,
38260
38278
  assets,
38261
38279
  themes,
38280
+ zenEnabled,
38262
38281
  graph,
38263
38282
  backlinks,
38264
38283
  files
@@ -38683,6 +38702,9 @@ function appShellHTML(serverInfo) {
38683
38702
  </html>`;
38684
38703
  }
38685
38704
  async function startServeServer(options) {
38705
+ process.on("unhandledRejection", (reason) => {
38706
+ console.error("crossnote serve: unhandled rejection:", reason);
38707
+ });
38686
38708
  const { rootDirectories, configContexts, notebooks } = await createNotebooksForDirectories(options.directories, {
38687
38709
  vscode: options.vscode,
38688
38710
  vscodeSettingsPath: options.vscodeSettingsPath,
@@ -38882,14 +38904,15 @@ async function startServeServer(options) {
38882
38904
  }
38883
38905
  case "setPreviewTheme":
38884
38906
  case "setCodeBlockTheme":
38885
- case "setRevealjsTheme": {
38886
- const configKey = command === "setPreviewTheme" ? "previewTheme" : command === "setCodeBlockTheme" ? "codeBlockTheme" : "revealjsTheme";
38887
- const theme = typeof args[1] === "string" ? args[1] : null;
38888
- if (!theme) {
38907
+ case "setRevealjsTheme":
38908
+ case "togglePreviewZenMode": {
38909
+ const configKey = command === "setPreviewTheme" ? "previewTheme" : command === "setCodeBlockTheme" ? "codeBlockTheme" : command === "setRevealjsTheme" ? "revealjsTheme" : "enablePreviewZenMode";
38910
+ const value = command === "togglePreviewZenMode" ? !notebooks[0].config.enablePreviewZenMode : typeof args[1] === "string" ? args[1] : null;
38911
+ if (value === null) {
38889
38912
  return;
38890
38913
  }
38891
38914
  try {
38892
- await updateServerConfigKey(configContexts[0], configKey, theme);
38915
+ await updateServerConfigKey(configContexts[0], configKey, value);
38893
38916
  await Promise.all(
38894
38917
  configContexts.map(async (context, index) => {
38895
38918
  const mergedConfig = await loadServerConfig(
@@ -38908,6 +38931,11 @@ async function startServeServer(options) {
38908
38931
  `crossnote serve: failed to persist ${configKey}:`,
38909
38932
  error
38910
38933
  );
38934
+ sse.broadcast({
38935
+ type: "notification",
38936
+ level: "error",
38937
+ message: `Failed to save "${configKey}": ${error instanceof Error ? error.message : String(error)}`
38938
+ });
38911
38939
  }
38912
38940
  return;
38913
38941
  }
@@ -38980,6 +39008,64 @@ async function startServeServer(options) {
38980
39008
  }
38981
39009
  return;
38982
39010
  }
39011
+ case "htmlExport":
39012
+ case "chromeExport":
39013
+ case "princeExport":
39014
+ case "eBookExport":
39015
+ case "pandocExport":
39016
+ case "markdownExport": {
39017
+ const sourceUri = assertFileWithinRoots(String(args[0] ?? ""));
39018
+ const param = args[1];
39019
+ if (!sourceUri || !isMarkdownFile(sourceUri)) {
39020
+ return;
39021
+ }
39022
+ const engine = notebookForFile(sourceUri)?.getNoteMarkdownEngine(sourceUri);
39023
+ if (!engine) {
39024
+ return;
39025
+ }
39026
+ try {
39027
+ let dest;
39028
+ if (command === "htmlExport") {
39029
+ dest = await engine.htmlExport({ offline: param === true });
39030
+ } else if (command === "chromeExport") {
39031
+ dest = await engine.chromeExport({
39032
+ fileType: typeof param === "string" ? param : "pdf"
39033
+ });
39034
+ } else if (command === "princeExport") {
39035
+ dest = await engine.princeExport({});
39036
+ if (dest.endsWith("?print-pdf")) {
39037
+ sse.broadcast({
39038
+ type: "notification",
39039
+ level: "info",
39040
+ message: `Please open the link below in Chrome and print it as PDF: ${dest}`
39041
+ });
39042
+ return;
39043
+ }
39044
+ } else if (command === "eBookExport") {
39045
+ dest = await engine.eBookExport({
39046
+ fileType: typeof param === "string" ? param : "epub",
39047
+ runAllCodeChunks: false
39048
+ });
39049
+ } else if (command === "pandocExport") {
39050
+ dest = await engine.pandocExport({});
39051
+ } else {
39052
+ dest = await engine.markdownExport({});
39053
+ }
39054
+ sse.broadcast({
39055
+ type: "notification",
39056
+ level: "info",
39057
+ message: `Exported ${path25.basename(sourceUri)} to ${dest}`
39058
+ });
39059
+ } catch (error) {
39060
+ console.error(`crossnote serve: ${command} failed:`, error);
39061
+ sse.broadcast({
39062
+ type: "notification",
39063
+ level: "error",
39064
+ message: `${command} failed: ${error instanceof Error ? error.message : String(error)}`
39065
+ });
39066
+ }
39067
+ return;
39068
+ }
38983
39069
  case "exportStandaloneWiki": {
38984
39070
  try {
38985
39071
  const result = await buildWiki({