const { execute_code } = require ( "@cocalc/backend/misc_node" ) ; import { callback_opts } from "@cocalc/util/async-utils" ; import ipynbToHtml , { htmlPath } from "./ipynb-to-html" ; import htmlToPDF from "./html-to-pdf" ; import { NbconvertParams , parseSource , parseTo } from "./util" ; import { join } from "path" ; import { getLogger } from "@cocalc/project/logger" ; import { sanitize_nbconvert_path } from "@cocalc/util/sanitize-nbconvert" ; const log = getLogger ( "jupyter-nbconvert" ) ; export async function nbconvert ( opts ) { log . debug ( "start" , opts ) ; try { if ( ! opts . timeout ) { opts . timeout = 30 ; } let { j , to } = parseTo ( opts . args ) ; if ( to == "cocalc-html" || to == "cocalc-pdf" ) { const ipynb = join ( opts . directory ?? "" , parseSource ( opts . args ) ) ; const html = await ipynbToHtml ( ipynb ) ; if ( to == "cocalc-html" ) { return ; } if ( to == "cocalc-pdf" ) { await htmlToPDF ( html , opts . timeout ) ; return ; } throw Error ( "impossible" ) ; } let convertToPDF = false ; const originalSource = parseSource ( opts . args ) ; if ( to == "lab-pdf" ) { for ( let i = 0 ; i < opts . args . length ; i ++ ) { if ( opts . args [ i ] == "lab-pdf" ) { opts . args [ i ] = "html" ; break ; } } to = "html" ; convertToPDF = true ; } else if ( to == "classic-pdf" ) { for ( let i = 0 ; i < opts . args . length ; i ++ ) { if ( opts . args [ i ] == "classic-pdf" ) { opts . args [ i ] = "html" ; break ; } } to = "html" ; convertToPDF = true ; opts . args = [ "--template" , "classic" ] . concat ( opts . args ) ; } let command ; let args ; if ( to === "sagews" ) { command = "smc-ipynb2sagews" ; args = opts . args . slice ( 0 , j ) . concat ( opts . args . slice ( j + 3 ) ) ; } else { command = "jupyter" ; args = [ "nbconvert" ] . concat ( opts . args ) ; args [ args . length - 1 ] = sanitize_nbconvert_path ( args [ args . length - 1 ] ) ; } log . debug ( "running " , { command , args } ) ; const output = await callback_opts ( execute_code ) ( { command , args , path : opts . directory , err_on_exit : false , timeout : opts . timeout , ulimit_timeout : true , bash : true , } ) ; if ( output . exit_code != 0 ) { throw Error ( output . stderr ) ; } if ( convertToPDF ) { await htmlToPDF ( htmlPath ( join ( opts . directory ?? "" , originalSource ) ) ) ; } } finally { log . debug ( "finished" ) ; } }