import express from "express" ; import { createServer } from "http" ; import { callback } from "awaiting" ; import compression from "compression" ; import bodyParser from "body-parser" ; import { join } from "path" ; import { writeFile } from "fs" ; import { once } from "@cocalc/util/async-utils" ; import { options } from "@cocalc/project/init-program" ; import basePath from "@cocalc/backend/base-path" ; import { getLogger } from "@cocalc/project/logger" ; import { browserPortFile , project_id } from "@cocalc/project/data" ; import initDirectoryListing from "@cocalc/project/directory-listing" ; import initJupyter from "@cocalc/project/jupyter/http-server" ; import initWebsocket from "@cocalc/project/browser-websocket/server" ; import initUpload from "@cocalc/project/upload" ; import initStaticServer from "./static" ; import initRootSymbolicLink from "./root-symlink" ; const kucalc = require ( "@cocalc/project/kucalc" ) ; const winston = getLogger ( "browser-http-server" ) ; export default async function init ( ) { winston . info ( "starting server..." ) ; const app = express ( ) ; const server = createServer ( app ) ; app . use ( compression ( ) ) ; app . use ( bodyParser . urlencoded ( { extended : true } ) ) ; app . use ( bodyParser . json ( ) ) ; winston . info ( "creating root symbolic link" ) ; await initRootSymbolicLink ( ) ; const base = join ( basePath , project_id , "raw" ) + "/" ; if ( kucalc . IN_KUCALC ) { winston . info ( "initializing KuCalc only health metrics server" ) ; kucalc . init_health_metrics ( app , project_id ) ; } winston . info ( "initializing directory listings server (DEPRECATED)" ) ; app . use ( base , initDirectoryListing ( ) ) ; winston . info ( "initializing Jupyter support HTTP server" ) ; ( async ( ) => { app . use ( base , await initJupyter ( ) ) ; } ) ( ) ; winston . info ( "initializing websocket server" ) ; app . use ( base , initWebsocket ( server , base ) ) ; winston . info ( "initializing file upload server" ) ; app . use ( base , initUpload ( ) ) ; winston . info ( "initializing static server" ) ; initStaticServer ( app , base ) ; server . listen ( options . browserPort , options . hostname ) ; await once ( server , "listening" ) ; const address = server . address ( ) ; if ( address == null || typeof address == "string" ) { throw Error ( "failed to assign a port" ) ; } const assignedPort = address . port ; winston . info ( `Started -- port=${ assignedPort }, host='${ options . hostname }', base='${ base }'` ) ; winston . info ( `Writing port to ${ browserPortFile }` ) ; await callback ( writeFile , browserPortFile , `${ assignedPort }` ) ; }