(() => {
var exports = {};
exports.id = 8504;
exports.ids = [8504];
exports.modules = {

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

"use strict";
module.exports = require("base-64");

/***/ }),

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

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

/***/ }),

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

"use strict";
module.exports = import("node-fetch");;

/***/ }),

/***/ 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");

/***/ }),

/***/ 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");

/***/ }),

/***/ 400768:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "ES": () => (/* binding */ defaultBranch),
/* harmony export */   "IQ": () => (/* binding */ contents),
/* harmony export */   "Kd": () => (/* binding */ rawText),
/* harmony export */   "en": () => (/* binding */ repos),
/* harmony export */   "eo": () => (/* binding */ RAW_MAX_SIZE_BYTES)
/* harmony export */ });
/* unused harmony exports api, fileInGist */
/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96544);
/* harmony import */ var base_64__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(102574);
/* harmony import */ var base_64__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(base_64__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(371017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(541808);
/* harmony import */ var _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cocalc_database_pool__WEBPACK_IMPORTED_MODULE_3__);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([node_fetch__WEBPACK_IMPORTED_MODULE_0__]);
node_fetch__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
/*
api.github.com is very nice to use to get info, but

"Unauthenticated clients can make **60 requests per hour**."
https://docs.github.com/en/rest/guides/getting-started-with-the-rest-api

So it's completely useless for our purposes without authentication.

"When authenticating, you should see your rate limit bumped to 5,000 requests an hour,"

which is also hopefully sufficient, but worrisome.

Thoughts:

- Since all rendering could be done client side, I could actually have
the client browser grab content instead of the server, then render there to
massively reduce api load, although even users could quickly hit "60 requests
per hour", so the api still wouldn't help.

- If we do hit the 5K/hour limit, maybe we can use more than one api key?

- Upgrading to enterprise doesn't increase this much.

- We could switch to mirroring and cloning files locally, and that might
  work around this problem in practice, but be a lot of work. We'll see.


Get at https://github.com/settings/tokens
*/ 



// We don't allow just fetching content that is arbitrarily large, since that could cause
// the server to just run out of memory.  However, we want this to reasonably big.
const RAW_MAX_SIZE_BYTES = 10000000; // 10MB
// TODO: we will also have a raw blob or stream or something for serving up images, etc.,
async function rawText(githubOrg, githubRepo, segments) {
    const url = rawURL(githubOrg, githubRepo, segments);
    //console.log("raw:", { url });
    return await (await (0,node_fetch__WEBPACK_IMPORTED_MODULE_0__["default"])(url, {
        size: RAW_MAX_SIZE_BYTES
    })).text();
}
function rawURL(githubOrg, githubRepo, segments) {
    return `https://raw.githubusercontent.com/${githubOrg}/${githubRepo}/${(0,path__WEBPACK_IMPORTED_MODULE_2__.join)(...segments.slice(1))}`;
}
async function credentials() {
    const pool = _cocalc_database_pool__WEBPACK_IMPORTED_MODULE_3___default()("long");
    const { rows  } = await pool.query("SELECT name, value FROM server_settings WHERE name='github_username' OR name='github_token'");
    let result = {};
    for (const row of rows){
        result[row.name] = row.value;
    }
    return result;
}
async function api(path) {
    const url = `https://api.github.com/${path}`;
    const options = {};
    const { github_username , github_token  } = await credentials();
    if (github_username && github_token) {
        options.headers = new node_fetch__WEBPACK_IMPORTED_MODULE_0__.Headers({
            Authorization: "Basic " + (0,base_64__WEBPACK_IMPORTED_MODULE_1__.encode)(`${github_username}:${github_token}`),
            "Content-Type": "application/json"
        });
    }
    //console.log(options);
    const response = await (0,node_fetch__WEBPACK_IMPORTED_MODULE_0__["default"])(url, options);
    //console.log(response.headers);
    const data = await response.json();
    //console.log({ url, response });
    if (data.message) {
        throw Error(`${data.message}  (see ${data.documentation_url})`);
    }
    return data;
}
// Use the github api to get the contents of a path on github.
// We are planning to use this just to get directory listings,
// since individual files have their content base64 encoded, etc.,
// and that has to be much slower than just grabbing the
// file form raw (and also only works up to 1MB according to
// github docs).
// How to do auth + fetch with node: https://stackoverflow.com/questions/43842793/basic-authentication-with-fetch
async function contents(githubOrg, githubRepo, segments) {
    let ref, path;
    if (segments.length == 0) {
        ref = ""; // the default;
        path = ""; // root
    } else {
        // tree/[ref]/[path ...]
        ref = segments[1];
        path = (0,path__WEBPACK_IMPORTED_MODULE_2__.join)(...segments.slice(2));
    }
    const result = await api(`repos/${githubOrg}/${githubRepo}/contents/${path}${ref ? "?ref=" + ref : ""}`);
    if (result.name != null) {
        throw Error("only use contents to get directory listing, not to get file contents");
    }
    return result;
}
async function defaultBranch(githubOrg, githubRepo) {
    return (await api(`repos/${githubOrg}/${githubRepo}`)).default_branch;
}
// Return all the repositories in a GitHub organization or user:
async function repos(githubOrg) {
    let result;
    try {
        result = await api(`orgs/${githubOrg}/repos`);
    } catch (err) {
        result = await api(`users/${githubOrg}/repos`);
    }
    return result.filter((repo)=>!repo.private).map((repo)=>{
        return {
            isdir: true,
            name: repo.name,
            mtime: new Date(repo.updated_at).valueOf(),
            url: `/github/${githubOrg}/${repo.name}`
        };
    });
}
async function fileInGist(gistId) {
    const info = await api(`gists/${gistId}`);
    for(const filename in info.files){
        return filename;
    }
    throw Error("no files in the gist");
}

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 847158:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getContents)
/* harmony export */ });
/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(400768);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(371017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _cocalc_util_cmp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(870328);
/* harmony import */ var _cocalc_util_cmp__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_cmp__WEBPACK_IMPORTED_MODULE_2__);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_api__WEBPACK_IMPORTED_MODULE_0__]);
_api__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 


async function getContents(githubOrg, githubRepo, segments) {
    if (!githubRepo) {
        // get all repos attached to an org
        const listing = await (0,_api__WEBPACK_IMPORTED_MODULE_0__/* .repos */ .en)(githubOrg);
        listing.sort((0,_cocalc_util_cmp__WEBPACK_IMPORTED_MODULE_2__.field_cmp)("mtime"));
        listing.reverse();
        return {
            listing
        };
    }
    switch(segments[0]){
        case undefined:
        case "tree":
            // directory listing
            const response = await (0,_api__WEBPACK_IMPORTED_MODULE_0__/* .contents */ .IQ)(githubOrg, githubRepo, segments);
            if (response["name"] != null) {
                // it's a file rather than a directory
                throw Error("not implemented");
            }
            const branch = segments[0] == null ? await (0,_api__WEBPACK_IMPORTED_MODULE_0__/* .defaultBranch */ .ES)(githubOrg, githubRepo) : segments[1];
            const listing1 = [];
            for (const file of response){
                const isdir = file.type == "dir";
                let url;
                if (isdir) {
                    if (segments[0] == null) {
                        url = `/github/${githubOrg}/${githubRepo}/${(0,path__WEBPACK_IMPORTED_MODULE_1__.join)("tree", branch, ...segments, file.name)}`;
                    } else {
                        url = `/github/${githubOrg}/${githubRepo}/${(0,path__WEBPACK_IMPORTED_MODULE_1__.join)(...segments, file.name)}`;
                    }
                } else {
                    if (segments[0] == null) {
                        url = `/github/${githubOrg}/${githubRepo}/${(0,path__WEBPACK_IMPORTED_MODULE_1__.join)("blob", branch, ...segments, file.name)}`;
                    } else {
                        url = `/github/${githubOrg}/${githubRepo}/${(0,path__WEBPACK_IMPORTED_MODULE_1__.join)("blob", segments[1], ...segments.slice(2), file.name)}`;
                    }
                }
                listing1.push({
                    url,
                    name: file.name,
                    isdir,
                    ...file.type == "file" ? {
                        size: file.size
                    } : undefined
                });
            }
            return {
                isdir: true,
                listing: listing1
            };
            break;
        case "blob":
            const content = await (0,_api__WEBPACK_IMPORTED_MODULE_0__/* .rawText */ .Kd)(githubOrg, githubRepo, segments);
            return {
                content,
                size: content.length
            };
        default:
            throw Error("not implemented");
    }
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 683043:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getProxiedPublicPathInfo)
/* harmony export */ });
/* harmony import */ var _get_public_path_info_github__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(88303);
/* harmony import */ var _get_public_path_info_url__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7586);
/* harmony import */ var _get_public_path_info_gist__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(262560);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(371017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_get_public_path_info_github__WEBPACK_IMPORTED_MODULE_0__, _get_public_path_info_url__WEBPACK_IMPORTED_MODULE_1__, _get_public_path_info_gist__WEBPACK_IMPORTED_MODULE_2__]);
([_get_public_path_info_github__WEBPACK_IMPORTED_MODULE_0__, _get_public_path_info_url__WEBPACK_IMPORTED_MODULE_1__, _get_public_path_info_gist__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);
// Get public path info for public path defined by url proxy which is assumed
// to already exist in the database.




``;
async function getProxiedPublicPathInfo(url, segments) {
    if (url.startsWith("github/")) {
        return await (0,_get_public_path_info_github__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)(segments == null ? url : (0,path__WEBPACK_IMPORTED_MODULE_3__.join)(url, ...segments.slice(1)));
    }
    if (url.startsWith("url/")) {
        return await (0,_get_public_path_info_url__WEBPACK_IMPORTED_MODULE_1__/* ["default"] */ .Z)(url);
    }
    if (url.startsWith("gist/")) {
        return await (0,_get_public_path_info_gist__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z)(url);
    }
    throw Error(`unknown proxy url schema -- "${url}"`);
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 262560:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getPublicPathInfoGist)
/* harmony export */ });
/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96544);
/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(400768);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([node_fetch__WEBPACK_IMPORTED_MODULE_0__, _api__WEBPACK_IMPORTED_MODULE_1__]);
([node_fetch__WEBPACK_IMPORTED_MODULE_0__, _api__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 

async function getPublicPathInfoGist(url // 'gist/user/gistId'
) {
    const v = url.split("/");
    if (v.length < 3) {
        throw Error(`invalid gist url - "${url}"`);
    }
    const [_, user, gistId] = v;
    const rawUrl = `https://gist.githubusercontent.com/${user}/${gistId}/raw/`;
    const content = await (await (0,node_fetch__WEBPACK_IMPORTED_MODULE_0__["default"])(rawUrl, {
        size: _api__WEBPACK_IMPORTED_MODULE_1__/* .RAW_MAX_SIZE_BYTES */ .eo
    })).text();
    return {
        contents: {
            content,
            size: content.length
        },
        relativePath: "",
        projectTitle: `${user}'s GitHub Gists -- https://gist.github.com/${user}`,
        githubOrg: user
    };
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 88303:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getPublicPathInfoGithub)
/* harmony export */ });
/* harmony import */ var _get_contents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(847158);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(371017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_1__);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([_get_contents__WEBPACK_IMPORTED_MODULE_0__]);
_get_contents__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 

async function getPublicPathInfoGithub(url) {
    const segments = url.split("/");
    const githubOrg = segments[1];
    if (!githubOrg) {
        throw Error(`invalid url ${url} -- must include github organization`);
    }
    const githubRepo = segments[2];
    const relativePath = (0,path__WEBPACK_IMPORTED_MODULE_1__.join)(...segments.slice(3));
    if (!githubRepo) {
        // only getting the repos for a single org.
        const contents = await (0,_get_contents__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)(githubOrg, "", []);
        const projectTitle = `GitHub Repositories owned by ${githubOrg}`;
        return {
            contents,
            relativePath,
            projectTitle,
            githubOrg
        };
    }
    const contents1 = await (0,_get_contents__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)(githubOrg, githubRepo, segments.slice(3));
    const projectTitle1 = `GitHub repository ${githubOrg} / ${githubRepo}`;
    return {
        contents: contents1,
        relativePath,
        projectTitle: projectTitle1,
        githubOrg,
        githubRepo,
        url
    };
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 7586:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "Z": () => (/* binding */ getPublicPathInfoUrl)
/* harmony export */ });
/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96544);
/* harmony import */ var _api__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(400768);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([node_fetch__WEBPACK_IMPORTED_MODULE_0__, _api__WEBPACK_IMPORTED_MODULE_1__]);
([node_fetch__WEBPACK_IMPORTED_MODULE_0__, _api__WEBPACK_IMPORTED_MODULE_1__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);
/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */ 

async function getPublicPathInfoUrl(url) {
    if (!url.startsWith("url/")) {
        throw Error("url must start with 'url/'");
    }
    // TODO: more than just text documents...
    let content = undefined;
    let err = undefined;
    for (const start of [
        "https://",
        "http://"
    ]){
        try {
            content = await (await (0,node_fetch__WEBPACK_IMPORTED_MODULE_0__["default"])(`${start}${url.slice("url/".length)}`, {
                size: _api__WEBPACK_IMPORTED_MODULE_1__/* .RAW_MAX_SIZE_BYTES */ .eo
            })).text();
            break;
        } catch (_err) {
            err = _err;
        }
    }
    if (content == null) {
        throw err;
    }
    return {
        contents: {
            content,
            size: content.length
        },
        relativePath: "",
        projectTitle: `Document at ${url}`
    };
};

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 153498:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__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 _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(854006);
/* harmony import */ var _cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(126804);
/* harmony import */ var _cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lib_api_get_params__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(26438);
/* harmony import */ var _cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(113011);
/* harmony import */ var _cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lib_share_proxy_get_proxied_public_path_info__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(683043);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([lib_share_proxy_get_proxied_public_path_info__WEBPACK_IMPORTED_MODULE_4__]);
lib_share_proxy_get_proxied_public_path_info__WEBPACK_IMPORTED_MODULE_4__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
/*
API endpoint to copy from a URL on the internet to a project.

This requires the user to be signed in with appropriate access to the project.

If project doesn't have network access, we stop the project, start it with
network access, get the content, then restart the project without network access.
*/ 





async function handle(req, res) {
    const params = (0,lib_api_get_params__WEBPACK_IMPORTED_MODULE_5__/* ["default"] */ .Z)(req);
    const error = checkParams(params);
    if (error) {
        res.json({
            error
        });
        return;
    }
    const { project_id , url , path  } = params;
    try {
        const account_id = await (0,lib_account_get_account__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .Z)(req);
        if (!account_id) {
            throw Error("must be signed in");
        }
        if (!_cocalc_server_projects_is_collaborator__WEBPACK_IMPORTED_MODULE_2___default()({
            account_id,
            project_id
        })) {
            throw Error("must be a collaborator on target project");
        }
        const info = await (0,lib_share_proxy_get_proxied_public_path_info__WEBPACK_IMPORTED_MODULE_4__/* ["default"] */ .Z)(url);
        if (info.contents?.content == null) {
            throw Error("copying of directories (e.g., GitHub repos) is not implemented");
        }
        const i = url.lastIndexOf("/");
        const filename = url.slice(i + 1);
        const mesg = {
            event: "write_text_file_to_project",
            path: path ? path : filename,
            content: info.contents.content
        };
        const response = await _cocalc_server_projects_connection_call__WEBPACK_IMPORTED_MODULE_3___default()({
            project_id,
            mesg
        });
        res.json({
            response
        });
    } catch (err) {
        res.json({
            error: `${err.message}`
        });
    }
};
function checkParams(obj) {
    if (!obj.url) return "url must be specified";
    if (!(0,_cocalc_util_misc__WEBPACK_IMPORTED_MODULE_1__.isValidUUID)(obj.project_id)) return "project_id must be a valid uuid";
}

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var handle_message_1 = __webpack_require__(386441);
var connect_1 = __importDefault(__webpack_require__(673317));
function call(_a) {
    var project_id = _a.project_id, mesg = _a.mesg;
    return __awaiter(this, void 0, void 0, function () {
        var socket;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, (0, connect_1.default)(project_id)];
                case 1:
                    socket = _b.sent();
                    return [4 /*yield*/, (0, handle_message_1.callProjectMessage)({ mesg: mesg, socket: socket })];
                case 2: return [2 /*return*/, _b.sent()];
            }
        });
    });
}
exports["default"] = call;
//# sourceMappingURL=call.js.map

/***/ }),

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

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var pool_1 = __importDefault(__webpack_require__(541808));
var misc_1 = __webpack_require__(854006);
function isCollaborator(_a) {
    var _b;
    var account_id = _a.account_id, project_id = _a.project_id;
    return __awaiter(this, void 0, void 0, function () {
        var pool, rows, group;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    if (!(0, misc_1.is_valid_uuid_string)(account_id) || !(0, misc_1.is_valid_uuid_string)(project_id)) {
                        throw Error("invalid input");
                    }
                    pool = (0, pool_1.default)("long");
                    return [4 /*yield*/, pool.query("SELECT users#>'{".concat(account_id, ",group}' AS group FROM projects WHERE project_id=$1"), [project_id])];
                case 1:
                    rows = (_c.sent()).rows;
                    group = (_b = rows[0]) === null || _b === void 0 ? void 0 : _b.group;
                    return [2 /*return*/, group == "owner" || group == "collaborator"];
            }
        });
    });
}
exports["default"] = isCollaborator;
//# sourceMappingURL=is-collaborator.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)
}


/***/ })

};
;

// 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, [549,6918,3429,8180,2921,2185,2014,6652,6942,1034,5751,2739,6257,9715,2448,1808,9738,8312,540,9459,8416,4181,3009,5016,6177,3086,8224,5970], () => (__webpack_exec__(153498)));
module.exports = __webpack_exports__;

})();