(() => {
var exports = {};
exports.id = 7099;
exports.ids = [7099,1225,1644,6394,7000,672,3533];
exports.modules = {

/***/ 439491:
/***/ ((module) => {

"use strict";
module.exports = require("assert");

/***/ }),

/***/ 714300:
/***/ ((module) => {

"use strict";
module.exports = require("buffer");

/***/ }),

/***/ 532081:
/***/ ((module) => {

"use strict";
module.exports = require("child_process");

/***/ }),

/***/ 435001:
/***/ ((module) => {

"use strict";
module.exports = require("cluster");

/***/ }),

/***/ 722057:
/***/ ((module) => {

"use strict";
module.exports = require("constants");

/***/ }),

/***/ 706113:
/***/ ((module) => {

"use strict";
module.exports = require("crypto");

/***/ }),

/***/ 809523:
/***/ ((module) => {

"use strict";
module.exports = require("dns");

/***/ }),

/***/ 582361:
/***/ ((module) => {

"use strict";
module.exports = require("events");

/***/ }),

/***/ 657147:
/***/ ((module) => {

"use strict";
module.exports = require("fs");

/***/ }),

/***/ 773292:
/***/ ((module) => {

"use strict";
module.exports = require("fs/promises");

/***/ }),

/***/ 113685:
/***/ ((module) => {

"use strict";
module.exports = require("http");

/***/ }),

/***/ 795687:
/***/ ((module) => {

"use strict";
module.exports = require("https");

/***/ }),

/***/ 241808:
/***/ ((module) => {

"use strict";
module.exports = require("net");

/***/ }),

/***/ 822037:
/***/ ((module) => {

"use strict";
module.exports = require("os");

/***/ }),

/***/ 371017:
/***/ ((module) => {

"use strict";
module.exports = require("path");

/***/ }),

/***/ 504074:
/***/ ((module) => {

"use strict";
module.exports = require("perf_hooks");

/***/ }),

/***/ 677282:
/***/ ((module) => {

"use strict";
module.exports = require("process");

/***/ }),

/***/ 514521:
/***/ ((module) => {

"use strict";
module.exports = require("readline");

/***/ }),

/***/ 12781:
/***/ ((module) => {

"use strict";
module.exports = require("stream");

/***/ }),

/***/ 371576:
/***/ ((module) => {

"use strict";
module.exports = require("string_decoder");

/***/ }),

/***/ 924404:
/***/ ((module) => {

"use strict";
module.exports = require("tls");

/***/ }),

/***/ 76224:
/***/ ((module) => {

"use strict";
module.exports = require("tty");

/***/ }),

/***/ 257310:
/***/ ((module) => {

"use strict";
module.exports = require("url");

/***/ }),

/***/ 473837:
/***/ ((module) => {

"use strict";
module.exports = require("util");

/***/ }),

/***/ 984655:
/***/ ((module) => {

"use strict";
module.exports = require("v8");

/***/ }),

/***/ 959796:
/***/ ((module) => {

"use strict";
module.exports = require("zlib");

/***/ }),

/***/ 26438:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getParams)
/* harmony export */ });
function getParams(req) {
    if (req?.method == "POST") {
        return new Proxy({}, {
            get (_, key) {
                return req.body?.[key];
            }
        });
    /*
    // Disabled, since this could lead to a sneaky click on a link attack.
    // Should only be enabled for dev purposes.
    } else if (req?.method == "GET") {
    return new Proxy(
      {},
      {
        get(_, key) {
          if (typeof key != "string") {
            return undefined;
          }
          return req.query?.[key];
        },
      }
    );
*/ } else {
        // only support params for POST requests.
        return {};
    }
}


/***/ }),

/***/ 851023:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handle)
/* harmony export */ });
/* harmony import */ var lib_account_get_account__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(559459);
/* harmony import */ var _projects_get_one__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(299013);
/* harmony import */ var _cocalc_server_projects_control__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(145970);
/* harmony import */ var _cocalc_server_projects_control__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_control__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _projects_call__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(219817);
/* harmony import */ var lib_api_get_params__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(26438);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(854006);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(223832);
/* harmony import */ var _cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(126804);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_6__);
/*
Turn latex file contents into a pdf.

You can call this either via GET or POST, but of course POST makes way more sense.
The parameters are:

- project_id: *optional* project in which to run latex.  If not given, your most recent project is used, or if you have no projects, one is created.
- content: *optional* textual content of the .tex file you want to latex.  If not given, path must refer to an actual file already in the project.
- path: required path to a .tex file.  If the file doesn't exist, it is created with the given content.  Also, if the directory containing path
  doesn't exist, it is created.
- command: *optional* latex build command.  This will be run from the directory containing path and should produce the output pdf file.
  If not given, we use latexmk.
- timeout: if given, this is a timeout on how long the latex build command can run before it is killed.
- ttl: how long the resulting PDF url is valid (default: 1 hour)


When you call this API the project is started if it isn't already running.  Then the path .tex file
is created, if content is specified.  Next the command is run which should hopefully produce a pdf file.
Finally, the pdf file is read into our database (as a blob), and the API call returns an object with
this shape:

{error?: '... message if something goes badly wrong ...',
compile: {
   stdout: string
   stderr: string
   exit_code: number
},
url: URL where you can view the generated PDF file
pdf: information about reading the PDF from disk, e.g., an
error if the PDF doesn't exist.

Finally, if the path starts with /tmp, e.g., /tmp/foo/bar.tex, then we do always do "rm /tmp/foo/bar.*"
to clean up temp file.  We do NOT do this unless the path starts with /tmp.


TODO/WARNING: For some reason on kucalc (so cocalc.com), if the project isn't running you'll
get an error while it is starting.  If you retry in a few seconds then it works.  On cocalc-docker
and dev mode it all seems to work fine in terms of starting the project, then using.
*/ 







async function handle(req, res) {
    const account_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)(req);
    const params = (0,lib_api_get_params__WEBPACK_IMPORTED_MODULE_7__/* ["default"] */ .Z)(req);
    try {
        if (!account_id) {
            throw Error("must be authenticated");
        }
        if (!params.path || !params.path.endsWith(".tex")) {
            throw Error("path must be specified and end in .tex");
        }
        const { head: dir , tail: filename  } = (0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_4__.path_split)(params.path);
        let project_id;
        if (params.project_id != null) {
            project_id = params.project_id;
            if (!await _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_6___default()({
                project_id,
                account_id
            })) {
                throw Error("must be signed in as a collaborator on the project");
            }
        } else {
            // don't need to check collaborator in this case:
            project_id = (await (0,_projects_get_one__WEBPACK_IMPORTED_MODULE_1__.getOneProject)(account_id)).project_id;
        }
        let result = undefined;
        try {
            // ensure the project is running.
            const project = (0,_cocalc_server_projects_control__WEBPACK_IMPORTED_MODULE_2__.getProject)(project_id);
            await project.start();
            if (params.content != null) {
                // write content to the project as the file path
                await (0,_projects_call__WEBPACK_IMPORTED_MODULE_3__.callProject)({
                    account_id,
                    project_id,
                    mesg: {
                        event: "write_text_file_to_project",
                        path: params.path,
                        content: params.content
                    }
                });
            }
            const compile = await (0,_projects_call__WEBPACK_IMPORTED_MODULE_3__.callProject)({
                account_id,
                project_id,
                mesg: {
                    event: "project_exec",
                    timeout: params.timeout,
                    path: dir,
                    command: params.command ?? `latexmk -pdf -f -g -bibtex -deps -interaction=nonstopmode ${filename}`
                }
            });
            // check for errors in compie before trying to read pdf. here...
            const ttlSeconds = params.ttl ?? 3600;
            const pdf = await (0,_projects_call__WEBPACK_IMPORTED_MODULE_3__.callProject)({
                account_id,
                project_id,
                mesg: {
                    event: "read_file_from_project",
                    path: pdfFile(params.path),
                    ttlSeconds
                }
            });
            const { siteURL  } = await _cocalc_server_settings_customize__WEBPACK_IMPORTED_MODULE_5___default()();
            const url = pdf.data_uuid ? siteURL + `/blobs/${pdfFile(params.path)}?uuid=${pdf.data_uuid}` : undefined;
            result = {
                compile,
                url,
                pdf
            };
        } finally{
            if (params.path.startsWith("/tmp")) {
                await (0,_projects_call__WEBPACK_IMPORTED_MODULE_3__.callProject)({
                    account_id,
                    project_id,
                    mesg: {
                        event: "project_exec",
                        path: "/tmp",
                        bash: true,
                        command: `rm ${rmGlob(params.path)}`
                    }
                });
            }
        }
        res.json(result);
    } catch (err) {
        res.json({
            error: err.message
        });
    }
}
function pdfFile(path) {
    return path.slice(0, path.length - 4) + ".pdf";
}
function rmGlob(path) {
    return path.slice(0, path.length - 4) + ".*";
}


/***/ }),

/***/ 219817:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "callProject": () => (/* binding */ callProject),
/* harmony export */   "default": () => (/* binding */ handle)
/* harmony export */ });
/* harmony import */ var _cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(113011);
/* harmony import */ var _cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lib_api_get_params__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26438);
/* harmony import */ var lib_account_get_account__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(559459);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(854006);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(126804);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3__);
/*
API endpoint that makes it possible to send a message to a project
that the user is a collaborator on and get back a response.

See cocalc/src/packages/server/projects/connection/call.ts
for a list of messages.
*/ 




async function handle(req, res) {
    const account_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z)(req);
    try {
        const { project_id , mesg  } = (0,lib_api_get_params__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .Z)(req);
        res.json(await callProject({
            account_id,
            project_id,
            mesg
        }));
    } catch (err) {
        res.json({
            error: err.message
        });
    }
}
// also used by the latex api call
async function callProject({ account_id , project_id , mesg ,  }) {
    if (!(0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_2__.isValidUUID)(account_id)) {
        throw Error("user must be authenticated");
    }
    if (!(0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_2__.isValidUUID)(project_id)) {
        throw Error("must specify project_id");
    }
    if (!await _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_3___default()({
        account_id,
        project_id
    })) {
        throw Error("authenticated user must be a collaborator on the project");
    }
    return await _cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_0___default()({
        project_id,
        mesg
    });
}


/***/ }),

/***/ 299013:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handle),
/* harmony export */   "getOneProject": () => (/* binding */ getOneProject)
/* harmony export */ });
/* harmony import */ var lib_account_get_account__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(559459);
/* harmony import */ var _cocalc_server_projects_create__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(713428);
/* harmony import */ var _cocalc_server_projects_create__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_create__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _cocalc_server_projects_get__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(483533);
/* harmony import */ var _cocalc_server_projects_get__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_get__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(854006);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_3__);
/* Get projects that belongs to the authenticated user.
   If the user has no projects, creates one.
   If they have projects, returns the most recently active one.
*/ 



async function handle(req, res) {
    const account_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)(req);
    try {
        res.json(await getOneProject(account_id));
    } catch (err) {
        res.json({
            error: err.message
        });
    }
}
// This is also used by the latex api endpoint.
async function getOneProject(account_id) {
    if (!(0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_3__.isValidUUID)(account_id)) {
        throw Error("user must be authenticated");
    }
    const projects = await _cocalc_server_projects_get__WEBPACK_IMPORTED_MODULE_2___default()({
        account_id,
        limit: 1
    });
    if (projects.length >= 1) {
        return projects[0];
    }
    const title = "Untitled Project";
    return {
        project_id: await _cocalc_server_projects_create__WEBPACK_IMPORTED_MODULE_1___default()({
            account_id,
            title
        }),
        title
    };
}


/***/ }),

/***/ 867000:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.associatedLicense = void 0;
const pool_1 = __importDefault(__webpack_require__(541808));
// Return the id of a site license if it should be applied to projects that use
// the given shared document.  Otherwise, return null;
async function associatedLicense(public_path_id) {
    const pool = (0, pool_1.default)("short");
    const { rows } = await pool.query("SELECT site_license_id, disabled, unlisted FROM public_paths WHERE id=$1", [public_path_id]);
    const { disabled, unlisted, site_license_id } = rows[0] ?? {};
    if (site_license_id && !disabled && unlisted) {
        // These are the only conditions under which we would apply a license.
        // Apply site_license_id to project_id.
        return site_license_id;
    }
    return null;
}
exports.associatedLicense = associatedLicense;
//# sourceMappingURL=public-path.js.map

/***/ }),

/***/ 113011:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
Use the project hub socket API to communicate with the project.

The supported messages are implemented here in the project:

   cocalc/src/packages/project/servers/hub/handle-message.ts

and messages must be defined as in

   cocalc/src/packages/util/message.js

and they include:

- ping: for testing; returns a pong
- heartbeat: used for maintaining the connection
- named_server_port: finding out the port used by jupyter, jupyterlab, etc.
- project_exec: run shell command
- read_file_from_project: reads file and stores it as a blob in the database. blob expires in 24 hours.
- write_file_to_project: write abitrary file to disk in project (goes via a blob)
- write_text_file_to_project: write a text file, whose contents is in the message, to the project.
- print_to_pdf: tells sage worksheet to print
- send_signal: send a signal to a process
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const handle_message_1 = __webpack_require__(386441);
const connect_1 = __importDefault(__webpack_require__(673317));
async function call({ project_id, mesg, }) {
    const socket = await (0, connect_1.default)(project_id);
    return await (0, handle_message_1.callProjectMessage)({ mesg, socket });
}
exports["default"] = call;
//# sourceMappingURL=call.js.map

/***/ }),

/***/ 713428:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const pool_1 = __importDefault(__webpack_require__(541808));
const software_envs_1 = __webpack_require__(465704);
const defaults_1 = __webpack_require__(294557);
const misc_1 = __webpack_require__(854006);
const uuid_1 = __webpack_require__(509557);
const public_path_1 = __webpack_require__(867000);
async function createProject({ account_id, title, description, image, license, public_path_id, }) {
    if (!(0, misc_1.is_valid_uuid_string)(account_id)) {
        throw Error("account_id must be a valid uuid");
    }
    const project_id = (0, uuid_1.v4)();
    const pool = (0, pool_1.default)();
    const users = { [account_id]: { group: "owner" } };
    let site_license;
    if (public_path_id) {
        const site_license_id = await (0, public_path_1.associatedLicense)(public_path_id);
        if (site_license_id) {
            if (!license) {
                license = site_license_id;
            }
            else {
                license = license + "," + site_license_id;
            }
        }
    }
    if (license) {
        site_license = {};
        for (const license_id of license.split(",")) {
            site_license[license_id] = {};
        }
    }
    else {
        site_license = undefined;
    }
    const envs = await (0, software_envs_1.getSoftwareEnvironments)("server");
    await pool.query("INSERT INTO projects (project_id, title, description, users, site_license, compute_image, created, last_edited) VALUES($1, $2, $3, $4, $5, $6, NOW(), NOW())", [
        project_id,
        title,
        description,
        JSON.stringify(users),
        site_license != null ? JSON.stringify(site_license) : undefined,
        image ?? envs?.default ?? defaults_1.DEFAULT_COMPUTE_IMAGE,
    ]);
    return project_id;
}
exports["default"] = createProject;
//# sourceMappingURL=create.js.map

/***/ }),

/***/ 483533:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/* get up to limit projects that have the given user as a collaborator,
   ordered by how recently they were modified.

   DELETED and HIDDEN projects are skipped.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const pool_1 = __importDefault(__webpack_require__(541808));
const misc_1 = __webpack_require__(854006);
// I may add more fields and more options later...
async function getProjects({ account_id, limit = 50, }) {
    if (!(0, misc_1.is_valid_uuid_string)(account_id)) {
        throw Error("account_id must be a UUIDv4");
    }
    if (limit <= 0) {
        return [];
    }
    const pool = (0, pool_1.default)();
    const { rows } = await pool.query(`SELECT project_id, title, description FROM projects WHERE DELETED IS NOT true AND users ? $1 AND (users#>>'{${account_id},hide}')::BOOLEAN IS NOT TRUE ORDER BY last_edited DESC LIMIT $2`, [account_id, limit]);
    return rows;
}
exports["default"] = getProjects;
//# sourceMappingURL=get.js.map

/***/ }),

/***/ 126804:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const pool_1 = __importDefault(__webpack_require__(541808));
const misc_1 = __webpack_require__(854006);
async function isCollaborator({ account_id, project_id, }) {
    if (!(0, misc_1.is_valid_uuid_string)(account_id) || !(0, misc_1.is_valid_uuid_string)(project_id)) {
        throw Error("invalid input");
    }
    const pool = (0, pool_1.default)("long"); // fine to cache "yes, you're a collab" for a while
    const { rows } = await pool.query(`SELECT users#>'{${account_id},group}' AS group FROM projects WHERE project_id=\$1`, [project_id]);
    const group = rows[0]?.group;
    return group == "owner" || group == "collaborator";
}
exports["default"] = isCollaborator;
//# sourceMappingURL=is-collaborator.js.map

/***/ }),

/***/ 223832:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const site_defaults_1 = __webpack_require__(889188);
const get_strategies_1 = __importDefault(__webpack_require__(728351));
const server_settings_1 = __webpack_require__(526177);
const site_url_1 = __importDefault(__webpack_require__(661348));
const fallback = (a, b) => typeof a == "string" && a.length > 0 ? a : `${b}`;
/*
Create a Javascript object that describes properties of the server.
This is used on the next.js server landing pages and the share server
to customize their look and behavior.

This function is cached via the parameters in ./server-settings, i.e.,
for a few seconds.
*/
let cachedSettings = undefined;
let cachedCustomize = undefined;
async function getCustomize() {
    const [settings, strategies] = await Promise.all([(0, server_settings_1.getServerSettings)(), (0, get_strategies_1.default)()]);
    if (settings === cachedSettings && cachedCustomize != null) {
        return cachedCustomize;
    }
    cachedSettings = settings;
    cachedCustomize = {
        siteName: fallback(settings.site_name, "On Premises CoCalc"),
        siteDescription: fallback(settings.site_description, "Collaborative Calculation using Python, Sage, R, Julia, and more."),
        organizationName: settings.organization_name,
        organizationEmail: settings.organization_email,
        organizationURL: settings.organization_url,
        termsOfServiceURL: settings.terms_of_service_url,
        helpEmail: settings.help_email,
        contactEmail: fallback(settings.organization_email, settings.help_email),
        isCommercial: settings.commercial,
        kucalc: settings.kucalc,
        sshGateway: settings.ssh_gateway,
        sshGatewayDNS: settings.ssh_gateway_dns,
        anonymousSignup: settings.anonymous_signup,
        emailSignup: settings.email_signup,
        accountCreationInstructions: settings.account_creation_email_instructions,
        logoSquareURL: settings.logo_square,
        logoRectangularURL: settings.logo_rectangular,
        splashImage: settings.splash_image,
        shareServer: !!settings.share_server,
        // additionally restrict showing landing pages only in cocalc.com-mode
        landingPages: !!settings.landing_pages && settings.kucalc === site_defaults_1.KUCALC_COCALC_COM,
        googleAnalytics: settings.google_analytics,
        indexInfo: settings.index_info_html,
        imprint: settings.imprint,
        policies: settings.policies,
        // Is important for invite emails, password reset, etc. (e.g., so we can construct a url to our site).
        // This *can* start with http:// to explicitly use http instead of https, and can end
        // in something like :3594 to indicate a port.
        dns: settings.dns,
        // siteURL is derived from settings.dns and the basePath -- it combines the dns, https://
        // and the basePath.  It never ends in a slash.  This is used in practice for
        // things like invite emails, password reset, etc.
        siteURL: await (0, site_url_1.default)(settings.dns),
        zendesk: settings.zendesk_token &&
            settings.zendesk_username &&
            settings.zendesk_uri,
        // obviously only the public key here!
        stripePublishableKey: settings.stripe_publishable_key,
        // obviously only the public key here too!
        reCaptchaKey: settings.re_captcha_v3_publishable_key,
        // a sandbox project
        sandboxProjectId: settings.sandbox_project_id,
        // GitHub proxy project
        githubProjectId: settings.github_project_id,
        // public info about SSO strategies
        strategies,
    };
    return cachedCustomize;
}
exports["default"] = getCustomize;
//# sourceMappingURL=customize.js.map

/***/ }),

/***/ 661348:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
const server_settings_1 = __webpack_require__(526177);
const base_path_1 = __importDefault(__webpack_require__(8312));
// Returns url of this site in terms of the base path (determined
// by an env variable when server starts) and the "Domain name"
// setting of site settings.  This URL does NOT end in a /
async function siteURL(dns) {
    if (!dns) {
        dns = (await (0, server_settings_1.getServerSettings)()).dns?.toLowerCase();
    }
    if (!dns) {
        dns = "localhost";
    }
    if (!dns.startsWith("http")) {
        dns = "https://" + dns;
    }
    return `${dns}${base_path_1.default == "/" ? "" : base_path_1.default}`;
}
exports["default"] = siteURL;
//# sourceMappingURL=site-url.js.map

/***/ }),

/***/ 465704:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {

"use strict";

/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getSoftwareEnvironments = void 0;
// This is used by the hub to adjust the "customization" variable for the user visible site, and also by manage in on-prem, to actually get the associated configuration
const logger_1 = __importDefault(__webpack_require__(227554));
const sanitize_software_envs_1 = __webpack_require__(13489);
const fs_1 = __webpack_require__(657147);
const promises_1 = __webpack_require__(773292);
const path_1 = __webpack_require__(371017);
const logger = (0, logger_1.default)("hub:webapp-config");
const L = logger.debug;
const W = logger.warn;
const cache = {
    server: null,
    webapp: null,
};
/**
 * A configuration for available software environments could be stored at the location of $COCALC_SOFTWARE_ENVIRONMENTS.
 */
async function getSoftwareEnvironments(purpose) {
    if (cache[purpose] === null) {
        cache[purpose] = (await readConfig(purpose)) ?? false;
    }
    const data = cache[purpose];
    return data === false ? null : data;
}
exports.getSoftwareEnvironments = getSoftwareEnvironments;
async function readConfig(purpose) {
    const dir = process.env.COCALC_SOFTWARE_ENVIRONMENTS;
    if (!dir)
        return null;
    // Check if a file "software.json" and "registry" exist and are readable at the directory "dir":
    const softwareFn = (0, path_1.join)(dir, "software.json");
    const registryFn = (0, path_1.join)(dir, "registry");
    if (!(await isReadable(softwareFn))) {
        W(`WARNING: $COCALC_SOFTWARE_ENVIRONMENTS is defined but ${softwareFn} does not exist`);
        return null;
    }
    if (!(await isReadable(registryFn))) {
        W(`WARNING: $COCALC_SOFTWARE_ENVIRONMENTS is defined but ${registryFn} does not exist`);
        return null;
    }
    // read the content of registry and trim it to a one line string
    const registry = (await (0, promises_1.readFile)(registryFn)).toString().trim();
    // parse the content of softwareFn as json
    try {
        const software = JSON.parse((await (0, promises_1.readFile)(softwareFn)).toString());
        const dbg = (...msg) => L(...msg);
        const sanitized = (0, sanitize_software_envs_1.sanitizeSoftwareEnv)({ software, registry, purpose }, dbg);
        return sanitized;
    }
    catch (err) {
        W(`WARNING: ${softwareFn} is not a valid JSON file -- ${err}`);
        return null;
    }
}
async function isReadable(path) {
    try {
        await (0, promises_1.access)(path, fs_1.constants.R_OK);
    }
    catch (err) {
        return false;
    }
    return true;
}
//# sourceMappingURL=software-envs.js.map

/***/ }),

/***/ 630900:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

var crypto = __webpack_require__(706113);

var rn = function(max) {
  var rnBytes = crypto.randomBytes(2);
  var randomNum = rnBytes.readUInt8(0) * 256 + rnBytes.readUInt8(1);
  return randomNum % max;
}

var digits = '0123456789'
var base62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'
var base30 = '0123456789ABCDFHKLMNPQRSTUVWXYZ'  // 1-9, A-Z exclude(E, G, I, J, O) for human read

exports.generate = function(len, chars) {
  len = len || 16;
  chars = chars || base62;
  var key = '';
  var charsLen = chars.length;
  for (var i=0; i<len; i++) {
    key += chars[rn(charsLen)];
  }
  return key;
};

exports.generateDigits = function(len) {
  len = len || 16;
  return exports.generate(len, digits)
};

exports.generateBase30 = function(len) {
  len = len || 16;
  return exports.generate(len, base30)
}


/***/ }),

/***/ 13489:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

/*
 *  This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.sanitizeSoftwareEnv = void 0;
const lodash_1 = __webpack_require__(131248);
const defaults_1 = __webpack_require__(294557);
const WEBAPP_RELEVANT = [
    "tag",
    "title",
    "registry",
    "descr",
    "order",
    "short",
    "group",
    "hidden",
];
// test if an object is an Environments map – does not need to be a precise test, because the sanitization fixes it
function isEnvironments(envs) {
    return (0, lodash_1.isObject)(envs) && Object.values(envs).every(lodash_1.isObject);
}
/**
 * Check that the "software environment" object is valid, set defaults, default exists, etc.
 *
 * If there is a problem, it logs it to the given logger and returns "null".
 *
 * purpose: "server" returns all values, while "webapp" only filters those, which are relevant for the webapp (and does not expose extra information)
 */
function sanitizeSoftwareEnv(opts, L) {
    const { software, registry, purpose } = opts;
    const envs = software["environments"];
    if ((0, lodash_1.isEmpty)(envs)) {
        L(`No software environments defined`);
        return null;
    }
    if (!isEnvironments(envs)) {
        L(`Software envs must be a map of strings to environment objects`);
        return null;
    }
    // make sure this is an array of strings
    const groups = (software["groups"] ?? []).map((x) => `${x}`);
    for (const key of Object.keys(envs)) {
        // if purpose is "webapp", only pick these entries in the env object: title, registry, tag, descr, order, short, group
        const env = purpose === "webapp" ? (0, lodash_1.pick)(envs[key], WEBAPP_RELEVANT) : envs[key];
        // if no registry is set, we're only using the id/key and the data
        // if the registry is set (in particular for on-prem) we use registry:tag to set the image
        if (registry != null) {
            if (typeof env["tag"] !== "string") {
                L(`WARNING: Environment ${key} has no "tag" field -- ignoring`);
                delete envs[key];
                continue;
            }
            env["registry"] = fallback(env["registry"], registry);
        }
        const group = fallback(env["group"], "General");
        env["group"] = group;
        env["title"] = fallback(env["title"], env["tag"], key);
        env["descr"] = fallback(env["descr"], "");
        if (!env["descr"])
            delete env["descr"];
        env["order"] = typeof env["order"] === "number" ? env["order"] : 0;
        if (env["order"] === 0)
            delete env["order"];
        if (!!env["hidden"]) {
            env["hidden"] = true;
        }
        else {
            delete env["hidden"];
        }
        envs[key] = { ...env, id: key };
        // if group is not in groups, add it
        if (!groups.includes(group)) {
            groups.push(group);
        }
    }
    // test that there is at leat one environemnt left in envs
    if ((0, lodash_1.isEmpty)(envs)) {
        L(`No software environments left after sanitization`);
        return null;
    }
    const swDflt = software["default"];
    // we check that the default is a string and that it exists in envs
    const dflt = typeof swDflt === "string" && envs[swDflt] != null
        ? swDflt
        : Object.keys(envs)[0];
    // this is a fallback entry, when projects were created before the software env was configured
    if (envs[defaults_1.DEFAULT_COMPUTE_IMAGE] == null) {
        envs[defaults_1.DEFAULT_COMPUTE_IMAGE] = { ...envs[dflt], hidden: true };
    }
    return { groups, default: dflt, environments: envs };
}
exports.sanitizeSoftwareEnv = sanitizeSoftwareEnv;
function fallback(a, b, c) {
    if (typeof a === "string")
        return a;
    if (typeof b === "string")
        return b;
    return c;
}
//# sourceMappingURL=sanitize-software-envs.js.map

/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [6918,1199,8180,2921,9557,5245,6652,6942,5517,6099,5751,2739,6257,8759,2003,1808,4006,8312,5710,9459,4181,4557,7896,6177,7710,4012,5970,8351], () => (__webpack_exec__(851023)));
module.exports = __webpack_exports__;

})();