"use strict";
var _this = this;
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var common_1 = require("./common");
exports.editorServer = function () {
    common_1.log.info.gray("Initializing " + common_1.log.magenta('editor.code') + " routes:\n");
    var router = common_1.express.router();
    var cache = {};
    var BASE_URL = common_1.constants.URL.BASE;
    var route = function (url, dir) {
        common_1.log.info.gray(" - route: " + common_1.log.cyan(url));
        common_1.log.info.gray(" - dir:   " + common_1.log.cyan(dir));
        common_1.log.info();
        var toPath = function (url) {
            if (url.startsWith(BASE_URL)) {
                return url.substr(BASE_URL.length + 1);
            }
            var index = url.indexOf('/vs/');
            if (index > -1) {
                return index > -1 ? url.substr(index + 4) : undefined;
            }
            return undefined;
        };
        router.get(url, function (req, res) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var done, path, cached, file, exists;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        done = function (file) {
                            cache[req.url] = { file: file };
                            return file ? res.sendFile(file) : res.status(404).send('Not found.');
                        };
                        path = toPath(req.url);
                        cached = cache[req.url];
                        if (cached) {
                            return [2, done(cached.file)];
                        }
                        if (!path || path.indexOf('..') > -1) {
                            return [2, done(undefined)];
                        }
                        file = common_1.fsPath.join(dir, path);
                        return [4, common_1.fs.pathExists(file)];
                    case 1:
                        exists = _a.sent();
                        if (!exists) {
                            return [2, done(undefined)];
                        }
                        if (common_1.constants.IS_DEV) {
                            common_1.log.info(common_1.log.magenta('GET'), common_1.log.cyan(req.url));
                            common_1.log.info.gray("    " + file);
                            common_1.log.info();
                        }
                        return [2, done(file)];
                }
            });
        }); });
    };
    route(BASE_URL + "/*", common_1.constants.EDITOR_RESOURCES.LOCAL);
    route("/vs/*", common_1.constants.VS.SOURCE);
    route("*/vs/*", common_1.constants.VS.SOURCE);
    return router;
};
//# sourceMappingURL=middleware.js.map