Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/backend/base-path.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/* Determine the base path for this CoCalc service.67The default export of this module is base path, which should8be used by the CoCalc backend hub server.9*/1011const DEFN: string = `12The basePath is the URL prefix for all paths, relative to the13host root. It must start with a leading slash /, but does not14end with one unless it is '/'. It also should not include ://.15Some examples of valid basePaths:1617- /18- /10f0e544-313c-4efe-8718-1111ac97ad11/port/50001920These are not valid:2122- //23- "" (empty string)24- /foo/25- https://cocalc.com/2627If the environment variable BASE_PATH is set then use that (e.g., used28when running a project), or throw an error if our assumptions are not satisfied.2930Otherwise, if this code is running in a CoCalc project (i.e., if the env variable31COCALC_PROJECT_ID is set), then the base path is a combination of32COCALC_PROJECT_ID and the port that the hub will serve on.3334If neither of the above conditions are met, then the base path is /.3536NOTES:3738- We use this code in a project started by the hub to determine the base path;39in that case, the env variable BASE_PATH is set, since otherwise the project40itself would view the base path as being relative to its own id.4142`;4344import PORT from "./port";4546function isValidBasePath(s: string): boolean {47if (s[0] != "/") return false;48if (s.length == 1) return true;49if (s[s.length - 1] == "/") return false;50if (s.includes("://")) return false;51return true;52}5354function basePath(): string {55if (process.env.BASE_PATH) {56if (!isValidBasePath(process.env.BASE_PATH)) {57throw Error(58`BASE_PATH (="${process.env.BASE_PATH}") is invalid - ${DEFN}.`,59);60}61return process.env.BASE_PATH;62}63if (process.env.API_SERVER) {64// if an api server is set but BASE_PATH isn't (e.g., we're using a remote api server), then we65// deduce the base path from that URL. Examples:66// API_SERVER=http://localhost:5000/6659c2e3-ff5e-4bb4-9a43-8830aa951282/port/5000 --> "/6659c2e3-ff5e-4bb4-9a43-8830aa951282/port/5000"67// API_SERVER=https://compute.cocalc.io --> "/"68// API_SERVER=https://cocalc.com --> "/"69const url = process.env.API_SERVER;70const i = url.indexOf("://");71if (i == -1) {72throw Error(`invalid API_SERVER url ${url}`);73}74const j = url.indexOf("/", i + 3);75if (j == -1) {76return "/";77}78return url.slice(j) ? url.slice(j) : "/";79}80if (!process.env.COCALC_PROJECT_ID) {81return "/";82}83// This is used by the project server, i.e., inside the project.84return `/${process.env.COCALC_PROJECT_ID}/port/${PORT}`;85}8687export default basePath();888990