"use strict";
exports.id = 1808;
exports.ids = [1808];
exports.modules = {

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


/*
Where Data is Stored:

We centralize here determination of all directories on the filesystem
where data is stored for any of the components of CoCalc, run in any way.

All information here must be determinable when this module is initialized,
e.g., from environment variables or heuristics involving the filesystem.
In particular, nothing here can be impacted by command line flags
or content of a database.
*/
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.logs = exports.secrets = exports.projects = exports.pgdatabase = exports.pghost = exports.pgdata = exports.pguser = exports.data = exports.root = void 0;
var DEFINITION = "CoCalc Environment Variables:\n- root -- if COCALC_ROOT is set then it; otherwise use [cocalc-source]/src/.\n- data -- if the environment variable DATA is set, use that.  Otherwise, use {root}/data\n- pgdata -- if env var PGDATA is set, use that; otherwise, it is {data}/postgres: where data data is stored (if running locally)\n- pghost - if env var PGHOST is set, use that; otherwise, it is {data}/postgres/socket: what database connects to\n- projects -- If env var PROJECTS is set, use that; otherwise, it is {data}\"/projects/[project_id]\";\n              This is where project home directories are (or shared files for share server), and it MUST\n              contain the string \"[project_id]\".\n- secrets -- if env var SECRETS is set, use that; otherwise, it is {data}/secrets:  where to store secrets\n- logs -- if env var LOGS is set, use that; otherwise, {data}/logs:  directory in which to store logs\n";
var path_1 = __webpack_require__(371017);
function determineRootFromPath() {
    var cur = __dirname;
    var search = "/src/";
    var i = cur.lastIndexOf(search);
    var root = (0, path_1.resolve)(cur.slice(0, i + search.length - 1));
    process.env.COCALC_ROOT = root;
    return root;
}
exports.root = (_a = process.env.COCALC_ROOT) !== null && _a !== void 0 ? _a : determineRootFromPath();
exports.data = (_b = process.env.DATA) !== null && _b !== void 0 ? _b : (0, path_1.join)(exports.root, "data");
exports.pguser = (_c = process.env.PGUSER) !== null && _c !== void 0 ? _c : "smc";
exports.pgdata = (_d = process.env.PGDATA) !== null && _d !== void 0 ? _d : (0, path_1.join)(exports.data, "postgres");
exports.pghost = (_e = process.env.PGHOST) !== null && _e !== void 0 ? _e : (0, path_1.join)(exports.pgdata, "socket");
exports.pgdatabase = (_g = (_f = process.env.SMC_DB) !== null && _f !== void 0 ? _f : process.env.PGDATABASE) !== null && _g !== void 0 ? _g : "smc";
exports.projects = (_h = process.env.PROJECTS) !== null && _h !== void 0 ? _h : (0, path_1.join)(exports.data, "projects", "[project_id]");
exports.secrets = (_j = process.env.SECRETS) !== null && _j !== void 0 ? _j : (0, path_1.join)(exports.data, "secrets");
exports.logs = (_k = process.env.LOGS) !== null && _k !== void 0 ? _k : (0, path_1.join)(exports.data, "logs");
function sanityChecks() {
    // Do a sanity check on projects:
    if (!exports.projects.includes("[project_id]")) {
        throw Error("".concat(DEFINITION, "\n\nenv variable PROJECTS must contain \"[project_id]\" but it is \"").concat(process.env.PROJECTS, "\""));
    }
}
sanityChecks();
//# sourceMappingURL=data.js.map

/***/ }),

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


/*
Debug logger for any node.js server.

There is used both by the hub(s) and project(s).

This is an implementation of basically how winston works for us,
but using the vastly simpler super-popular debug module.
*/
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.setCounter = exports.getLogger = void 0;
// setting env var must come *BEFORE* debug is loaded the first time
process.env.DEBUG_HIDE_DATE = "yes"; // since we supply it ourselves
// otherwise, maybe stuff like this works: (debug as any).inspectOpts["hideDate"] = true;
var debug_1 = __importDefault(__webpack_require__(511050));
var fs_1 = __webpack_require__(657147);
var util_1 = __webpack_require__(473837);
var path_1 = __webpack_require__(371017);
var data_1 = __webpack_require__(221945);
var COCALC = (0, debug_1.default)("cocalc");
function myFormat() {
    var e_1, _a;
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    if (args.length > 1 && typeof args[0] == "string" && !args[0].includes("%")) {
        // This is something where we didn't use printf formatting.
        var v = [];
        try {
            for (var args_1 = __values(args), args_1_1 = args_1.next(); !args_1_1.done; args_1_1 = args_1.next()) {
                var x = args_1_1.value;
                try {
                    v.push(typeof x == "object" ? JSON.stringify(x) : "".concat(x));
                }
                catch (_) {
                    // better to not crash everything just for logging
                    v.push("".concat(x));
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (args_1_1 && !args_1_1.done && (_a = args_1.return)) _a.call(args_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return v.join(" ");
    }
    // use printf formatting.
    return util_1.format.apply(void 0, __spreadArray([], __read(args), false));
}
function defaultTransports() {
    if (process.env.SMC_TEST) {
        return {};
    }
    else if (process.env.COCALC_DOCKER) {
        return { file: "/var/log/hub/log" };
    }
    else if (true) {
        return { console: true };
    }
    else {}
}
function initTransports() {
    if (!process.env.DEBUG) {
        // if DEBUG isn't set then the debug logger will be silent anyways.
        return;
    }
    var transports = defaultTransports();
    if (process.env.DEBUG_CONSOLE != null) {
        transports.console =
            process.env.DEBUG_CONSOLE != "no" && process.env.DEBUG_CONSOLE != "false";
    }
    if (process.env.DEBUG_FILE != null) {
        transports.file = process.env.DEBUG_FILE;
    }
    var fileStream;
    if (transports.file) {
        // ensure directory exists
        (0, fs_1.mkdirSync)((0, path_1.dirname)(transports.file), { recursive: true });
        // create the file stream; using a stream ensures
        // that everything is written in the right order with
        // no corruption/collision between different logging.
        fileStream = (0, fs_1.createWriteStream)(transports.file);
    }
    var firstLog = true;
    COCALC.log = function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        if (!transports.file && !transports.console)
            return;
        if (firstLog && transports.file) {
            console.error("***\n\nLogging to \"".concat(transports.file, "\"").concat(transports.console ? " and console.error" : "", " via the debug module\nwith  DEBUG='").concat(process.env.DEBUG, "'.\nUse   DEBUG_FILE='path' and DEBUG_CONSOLE=[yes|no] to override.\nUsing DEBUG='cocalc:*,-cocalc:silly:*' to control log levels.\n\n***"));
            firstLog = false;
        }
        // Similar as in debug source code, except I stuck a timestamp
        // at the beginning, which I like... except also aware of
        // non-printf formatting.
        var line = "".concat(new Date().toISOString(), ": ").concat(myFormat.apply(void 0, __spreadArray([], __read(args), false)), "\n");
        if (transports.console) {
            // the console transport:
            console.error(line);
        }
        if (transports.file) {
            // the file transport
            fileStream.write(line);
        }
    };
}
initTransports();
var DEBUGGERS = {
    error: COCALC.extend("error"),
    warn: COCALC.extend("warn"),
    info: COCALC.extend("info"),
    http: COCALC.extend("http"),
    verbose: COCALC.extend("verbose"),
    debug: COCALC.extend("debug"),
    silly: COCALC.extend("silly"),
};
var LEVELS = [
    "error",
    "warn",
    "info",
    "http",
    "verbose",
    "debug",
    "silly",
];
var Logger = /** @class */ (function () {
    function Logger(name) {
        var e_2, _a;
        var _this = this;
        this.debuggers = {};
        this.name = name;
        var _loop_1 = function (level) {
            this_1.debuggers[level] = DEBUGGERS[level].extend(name);
            this_1[level] = function () {
                var _a;
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                _this.counter("error");
                // @ts-ignore
                (_a = _this.debuggers)[level].apply(_a, __spreadArray([], __read(args), false));
            };
        };
        var this_1 = this;
        try {
            for (var LEVELS_1 = __values(LEVELS), LEVELS_1_1 = LEVELS_1.next(); !LEVELS_1_1.done; LEVELS_1_1 = LEVELS_1.next()) {
                var level = LEVELS_1_1.value;
                _loop_1(level);
            }
        }
        catch (e_2_1) { e_2 = { error: e_2_1 }; }
        finally {
            try {
                if (LEVELS_1_1 && !LEVELS_1_1.done && (_a = LEVELS_1.return)) _a.call(LEVELS_1);
            }
            finally { if (e_2) throw e_2.error; }
        }
    }
    Logger.prototype.extend = function (name) {
        return new Logger("".concat(this.name, ":").concat(name));
    };
    Logger.prototype.counter = function (level) {
        if (counter == null)
            return;
        counter.labels(this.name, level).inc(1);
    };
    return Logger;
}());
var cache = {};
function getLogger(name) {
    if (cache[name] != null) {
        return cache[name];
    }
    // smash it over since we build Logger pretty generically so typescript
    // doesn't get it.  But we care that all *client* code uses the WinstonLogger
    // interface.
    return (cache[name] = new Logger(name));
}
exports["default"] = getLogger;
exports.getLogger = getLogger;
var counter = undefined;
function setCounter(f) {
    counter = f;
}
exports.setCounter = setCounter;
//# sourceMappingURL=logger.js.map

/***/ }),

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


/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
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 __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
/*
Caches queries for a certain amount of time.
Also, if there are multiple queries coming in
at the same time for the same thing, only
one actually goes to the database.

IMPORTANT: This *only* caches a query if the query actually
returns at least one row.  If the query returns nothing,
that fact is not cached.  This is usually what we want, e.g.,
if somebody access https://cocalc.com/wstein/myproject, and
notices that myproject isn't the set name, then they may
set it and immediately try  https://cocalc.com/wstein/myproject again.
In that case, we don't want to the cache to mean that they don't
see the page for a while. On the other hand, if querying for the
project that myproject resolves to is cached for a minute that is
fine, since this would only be a problem when they change the name
of multiple projects.
*/
var lru_cache_1 = __importDefault(__webpack_require__(35240));
var hof_1 = __webpack_require__(111735);
var pool_1 = __importDefault(__webpack_require__(63248));
var logger_1 = __importDefault(__webpack_require__(227554));
var L = (0, logger_1.default)("db:pool:cached");
var MAX_AGE_S = {
    short: 5,
    medium: 15,
    long: 30,
    minutes: 10 * 60,
    infinite: 60 * 60 * 24 * 365, // effectively forever; e.g., getting path from share id is really just a reversed sha1 hash, so can't change.
};
var caches = new Map();
for (var length in MAX_AGE_S) {
    caches[length] = new lru_cache_1.default({
        max: 1000,
        maxAge: 1000 * MAX_AGE_S[length],
    });
}
var cachedQuery = (0, hof_1.reuseInFlight)(function (length) {
    var args = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
    }
    return __awaiter(void 0, void 0, void 0, function () {
        var cache, key, pool, result, err_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    cache = caches[length];
                    if (cache == null) {
                        throw Error("invalid cache \"".concat(length, "\""));
                    }
                    key = JSON.stringify(args);
                    if (cache.has(key)) {
                        // console.log(`YES - using cache for ${key}`);
                        return [2 /*return*/, cache.get(key)];
                    }
                    pool = (0, pool_1.default)();
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, pool.query.apply(pool, __spreadArray([], __read(args), false))];
                case 2:
                    result = _a.sent();
                    if (result.rows.length > 0) {
                        // We only cache query if it returned something.
                        cache.set(key, result);
                    }
                    return [2 /*return*/, result];
                case 3:
                    err_1 = _a.sent();
                    L.error("cachedQuery error: ".concat(err_1));
                    throw err_1;
                case 4: return [2 /*return*/];
            }
        });
    });
});
function getCachedPool(length) {
    var _this = this;
    return {
        query: function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, cachedQuery.apply(void 0, __spreadArray([length], __read(args), false))];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            }); });
        },
    }; // obviously not really a Pool, but is enough for what we're doing.
}
exports["default"] = getCachedPool;
//# sourceMappingURL=cached.js.map

/***/ }),

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


/*
 *  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.timeInSeconds = void 0;
var pool_1 = __importDefault(__webpack_require__(63248));
exports["default"] = pool_1.default;
var util_1 = __webpack_require__(258813);
Object.defineProperty(exports, "timeInSeconds", ({ enumerable: true, get: function () { return util_1.timeInSeconds; } }));
//# sourceMappingURL=index.js.map

/***/ }),

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


Object.defineProperty(exports, "__esModule", ({ value: true }));
var path_1 = __webpack_require__(371017);
var data_1 = __webpack_require__(221945);
var fs_1 = __webpack_require__(657147);
function dbPassword() {
    var filename = (0, path_1.join)(data_1.secrets, "postgres");
    try {
        // fine to use sync, since reading db password happens only on startup
        return (0, fs_1.readFileSync)(filename).toString().trim();
    }
    catch (_a) {
        return undefined;
    }
}
exports["default"] = dbPassword;
//# sourceMappingURL=password.js.map

/***/ }),

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


/*
 *  This file is part of CoCalc: Copyright © 2021 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
var data_1 = __webpack_require__(221945);
var pg_1 = __webpack_require__(810758);
var cached_1 = __importDefault(__webpack_require__(755376));
var password_1 = __importDefault(__webpack_require__(184457));
var logger_1 = __webpack_require__(227554);
var L = (0, logger_1.getLogger)("db:pool");
__exportStar(__webpack_require__(258813), exports);
var pool = undefined;
function getPool(cacheLength) {
    if (cacheLength != null) {
        return (0, cached_1.default)(cacheLength);
    }
    if (pool == null) {
        L.debug("creating a new Pool");
        pool = new pg_1.Pool({ password: (0, password_1.default)(), user: data_1.pguser, host: data_1.pghost, database: data_1.pgdatabase });
    }
    return pool;
}
exports["default"] = getPool;
//# sourceMappingURL=pool.js.map

/***/ }),

/***/ 258813:
/***/ ((__unused_webpack_module, exports) => {


/*
 *  This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
 *  License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
 */
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.expireTime = exports.timeInSeconds = void 0;
// Postgres 14 is different than 13 an earlier.
// extract(epoch from timestamp) returns a "numeric", which is converted to a string by the pg driver.
// we convert this explicitly to a floating point number to get the ms since epoch.
// Note: JavaScript's new Date(...) has no hesitation converting from a float.
function timeInSeconds(field, asField) {
    return " (EXTRACT(EPOCH FROM ".concat(field, ")*1000)::FLOAT as ").concat(asField !== null && asField !== void 0 ? asField : field, " ");
}
exports.timeInSeconds = timeInSeconds;
// Given number of seconds **in the future**.
function expireTime(ttl_s) {
    if (ttl_s === void 0) { ttl_s = 0; }
    return new Date(new Date().valueOf() + ttl_s * 1000);
}
exports.expireTime = expireTime;
//# sourceMappingURL=util.js.map

/***/ })

};
;