@learnpack/learnpack 2.1.27 → 2.1.29

Sign up to get free protection for your applications and to get access to all the features.
Files changed (117) hide show
  1. package/README.md +10 -10
  2. package/lib/commands/audit.d.ts +6 -0
  3. package/lib/commands/audit.js +342 -0
  4. package/lib/commands/clean.d.ts +8 -0
  5. package/lib/commands/clean.js +25 -0
  6. package/lib/commands/download.d.ts +13 -0
  7. package/lib/commands/download.js +55 -0
  8. package/lib/commands/init.d.ts +9 -0
  9. package/lib/commands/init.js +123 -0
  10. package/lib/commands/login.d.ts +14 -0
  11. package/lib/commands/login.js +37 -0
  12. package/lib/commands/logout.d.ts +14 -0
  13. package/lib/commands/logout.js +37 -0
  14. package/lib/commands/publish.d.ts +14 -0
  15. package/lib/commands/publish.js +82 -0
  16. package/lib/commands/start.d.ts +7 -0
  17. package/lib/commands/start.js +176 -0
  18. package/lib/commands/test.d.ts +6 -0
  19. package/lib/commands/test.js +62 -0
  20. package/lib/index.d.ts +1 -0
  21. package/lib/index.js +4 -0
  22. package/lib/managers/config/allowed_files.d.ts +5 -0
  23. package/lib/managers/config/allowed_files.js +30 -0
  24. package/lib/managers/config/defaults.d.ts +39 -0
  25. package/lib/managers/config/defaults.js +40 -0
  26. package/lib/managers/config/exercise.d.ts +36 -0
  27. package/lib/managers/config/exercise.js +233 -0
  28. package/lib/managers/config/index.d.ts +3 -0
  29. package/lib/managers/config/index.js +320 -0
  30. package/lib/managers/file.d.ts +14 -0
  31. package/lib/managers/file.js +141 -0
  32. package/lib/managers/gitpod.d.ts +3 -0
  33. package/lib/managers/gitpod.js +67 -0
  34. package/lib/managers/server/index.d.ts +6 -0
  35. package/lib/managers/server/index.js +58 -0
  36. package/lib/managers/server/routes.d.ts +4 -0
  37. package/lib/managers/server/routes.js +201 -0
  38. package/lib/managers/session.d.ts +3 -0
  39. package/lib/managers/session.js +131 -0
  40. package/lib/managers/socket.d.ts +3 -0
  41. package/lib/managers/socket.js +178 -0
  42. package/lib/managers/test.d.ts +0 -0
  43. package/lib/managers/test.js +84 -0
  44. package/lib/models/action.d.ts +2 -0
  45. package/lib/models/action.js +2 -0
  46. package/lib/models/audit.d.ts +15 -0
  47. package/lib/models/audit.js +2 -0
  48. package/lib/models/config-manager.d.ts +21 -0
  49. package/lib/models/config-manager.js +2 -0
  50. package/lib/models/config.d.ts +62 -0
  51. package/lib/models/config.js +2 -0
  52. package/lib/models/counter.d.ts +11 -0
  53. package/lib/models/counter.js +2 -0
  54. package/lib/models/errors.d.ts +15 -0
  55. package/lib/models/errors.js +2 -0
  56. package/lib/models/exercise-obj.d.ts +30 -0
  57. package/lib/models/exercise-obj.js +2 -0
  58. package/lib/models/file.d.ts +5 -0
  59. package/lib/models/file.js +2 -0
  60. package/lib/models/findings.d.ts +17 -0
  61. package/lib/models/findings.js +2 -0
  62. package/lib/models/flags.d.ts +10 -0
  63. package/lib/models/flags.js +2 -0
  64. package/lib/models/front-matter.d.ts +11 -0
  65. package/lib/models/front-matter.js +2 -0
  66. package/lib/models/gitpod-data.d.ts +16 -0
  67. package/lib/models/gitpod-data.js +2 -0
  68. package/lib/models/language.d.ts +4 -0
  69. package/lib/models/language.js +2 -0
  70. package/lib/models/package.d.ts +7 -0
  71. package/lib/models/package.js +2 -0
  72. package/lib/models/plugin-config.d.ts +16 -0
  73. package/lib/models/plugin-config.js +2 -0
  74. package/lib/models/session.d.ts +26 -0
  75. package/lib/models/session.js +2 -0
  76. package/lib/models/socket.d.ts +32 -0
  77. package/lib/models/socket.js +2 -0
  78. package/lib/models/status.d.ts +1 -0
  79. package/lib/models/status.js +2 -0
  80. package/lib/models/success-types.d.ts +1 -0
  81. package/lib/models/success-types.js +2 -0
  82. package/lib/plugin/command/compile.d.ts +6 -0
  83. package/lib/plugin/command/compile.js +18 -0
  84. package/lib/plugin/command/test.d.ts +6 -0
  85. package/lib/plugin/command/test.js +25 -0
  86. package/lib/plugin/index.d.ts +27 -0
  87. package/lib/plugin/index.js +7 -0
  88. package/lib/plugin/plugin.d.ts +8 -0
  89. package/lib/plugin/plugin.js +68 -0
  90. package/lib/plugin/utils.d.ts +16 -0
  91. package/lib/plugin/utils.js +58 -0
  92. package/lib/ui/download.d.ts +5 -0
  93. package/lib/ui/download.js +61 -0
  94. package/lib/utils/BaseCommand.d.ts +8 -0
  95. package/lib/utils/BaseCommand.js +41 -0
  96. package/lib/utils/SessionCommand.d.ts +10 -0
  97. package/lib/utils/SessionCommand.js +47 -0
  98. package/lib/utils/api.d.ts +14 -0
  99. package/lib/utils/api.js +218 -0
  100. package/lib/utils/audit.d.ts +16 -0
  101. package/lib/utils/audit.js +302 -0
  102. package/lib/utils/console.d.ts +12 -0
  103. package/lib/utils/console.js +19 -0
  104. package/lib/utils/errors.d.ts +17 -0
  105. package/lib/utils/errors.js +100 -0
  106. package/lib/utils/exercisesQueue.d.ts +9 -0
  107. package/lib/utils/exercisesQueue.js +38 -0
  108. package/lib/utils/fileQueue.d.ts +40 -0
  109. package/lib/utils/fileQueue.js +168 -0
  110. package/lib/utils/misc.d.ts +1 -0
  111. package/lib/utils/misc.js +23 -0
  112. package/lib/utils/validators.d.ts +5 -0
  113. package/lib/utils/validators.js +17 -0
  114. package/lib/utils/watcher.d.ts +2 -0
  115. package/lib/utils/watcher.js +23 -0
  116. package/oclif.manifest.json +1 -1
  117. package/package.json +2 -1
@@ -0,0 +1,14 @@
1
+ export declare const decompress: (sourcePath: string, destinationPath: string) => Promise<unknown>;
2
+ export declare const downloadEditor: (version: string | undefined, destination: string) => Promise<unknown>;
3
+ export declare const download: (url: string, dest: string) => Promise<unknown>;
4
+ export declare const clone: (repository?: string, folder?: string) => Promise<unknown>;
5
+ export declare const rmSync: (path: string) => void;
6
+ export declare const checkIfDirectoryExists: (path: string) => boolean;
7
+ declare const _default: {
8
+ download: (url: string, dest: string) => Promise<unknown>;
9
+ decompress: (sourcePath: string, destinationPath: string) => Promise<unknown>;
10
+ downloadEditor: (version: string | undefined, destination: string) => Promise<unknown>;
11
+ clone: (repository?: string, folder?: string) => Promise<unknown>;
12
+ rmSync: (path: string) => void;
13
+ };
14
+ export default _default;
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkIfDirectoryExists = exports.rmSync = exports.clone = exports.download = exports.downloadEditor = exports.decompress = void 0;
4
+ const fs = require("fs");
5
+ const p = require("path");
6
+ const shell = require("shelljs");
7
+ const cli_ux_1 = require("cli-ux");
8
+ const targz = require("targz");
9
+ const console_1 = require("../utils/console");
10
+ const https = require("https");
11
+ const errors_1 = require("../utils/errors");
12
+ // eslint-disable-next-line
13
+ const fetch = require("node-fetch");
14
+ exports.decompress = (sourcePath, destinationPath) => new Promise((resolve, reject) => {
15
+ console_1.default.debug("Decompressing " + sourcePath);
16
+ targz.decompress({
17
+ src: sourcePath,
18
+ dest: destinationPath,
19
+ }, function (err) {
20
+ if (err) {
21
+ console_1.default.error("Error when trying to decompress");
22
+ reject(err);
23
+ }
24
+ else {
25
+ console_1.default.info("Decompression finished successfully");
26
+ resolve(/* */ "");
27
+ }
28
+ });
29
+ });
30
+ exports.downloadEditor = async (version, destination) => {
31
+ // https://raw.githubusercontent.com/learnpack/coding-ide/master/dist/app.tar.gz
32
+ // if(versions[version] === undefined) throw new Error(`Invalid editor version ${version}`)
33
+ const resp2 = await fetch(`https://github.com/learnpack/coding-ide/blob/${version}/dist`, { method: "HEAD" });
34
+ if (!resp2.ok)
35
+ throw errors_1.InternalError(`Coding Editor ${version} was not found on learnpack repository, check the config.editor.version property on learn.json`);
36
+ console_1.default.info("Downloading the LearnPack coding UI, this may take a minute...");
37
+ return exports.download(`https://github.com/learnpack/coding-ide/blob/${version}/dist/app.tar.gz?raw=true`, destination);
38
+ };
39
+ exports.download = (url, dest) => {
40
+ console_1.default.debug("Downloading " + url);
41
+ return new Promise((resolve, reject) => {
42
+ const request = https.get(url, response => {
43
+ if (response.statusCode === 200) {
44
+ const file = fs.createWriteStream(dest, { flags: "wx" });
45
+ file.on("finish", () => {
46
+ resolve(true);
47
+ });
48
+ file.on("error", err => {
49
+ file.close();
50
+ if (err.code === "EEXIST") {
51
+ console_1.default.debug("File already exists");
52
+ resolve("File already exists");
53
+ }
54
+ else {
55
+ console_1.default.debug("Error ", err.message);
56
+ fs.unlink(dest, () => reject(err.message)); // Delete temp file
57
+ }
58
+ });
59
+ response.pipe(file);
60
+ }
61
+ else if (response.statusCode === 302 || response.statusCode === 301) {
62
+ // Console.debug("Servers redirected to "+response.headers.location)
63
+ // Recursively follow redirects, only a 200 will resolve.
64
+ if (response.headers.location) {
65
+ exports.download(response.headers.location, dest)
66
+ .then(() => resolve(/* */ ""))
67
+ .catch(error => {
68
+ console_1.default.error(error);
69
+ reject(error);
70
+ });
71
+ }
72
+ }
73
+ else {
74
+ console_1.default.debug(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
75
+ reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
76
+ }
77
+ });
78
+ request.on("error", err => {
79
+ reject(err.message);
80
+ });
81
+ });
82
+ };
83
+ exports.clone = (repository = "", folder = "./") => new Promise((resolve, reject) => {
84
+ if (!repository) {
85
+ reject("Missing repository url for this package");
86
+ // return false
87
+ }
88
+ cli_ux_1.cli.action.start("Verifying GIT...");
89
+ if (!shell.which("git")) {
90
+ reject("Sorry, this script requires git");
91
+ // return false
92
+ }
93
+ cli_ux_1.cli.action.stop();
94
+ let fileName = p.basename(repository);
95
+ if (!fileName) {
96
+ reject("Invalid repository information on package: " + repository);
97
+ // return false
98
+ }
99
+ fileName = fileName.split(".")[0];
100
+ if (fs.existsSync("./" + fileName)) {
101
+ reject(`Directory ${fileName} already exists; Did you download this package already?`);
102
+ // return false
103
+ }
104
+ cli_ux_1.cli.action.start(`Cloning repository ${repository}...`);
105
+ if (shell.exec(`git clone ${repository}`).code !== 0) {
106
+ reject("Error: Installation failed");
107
+ }
108
+ cli_ux_1.cli.action.stop();
109
+ cli_ux_1.cli.action.start("Cleaning installation...");
110
+ if (shell.exec(`rm -R -f ${folder}${fileName}/.git`).code !== 0) {
111
+ reject("Error: removing .git directory");
112
+ }
113
+ cli_ux_1.cli.action.stop();
114
+ resolve("Done");
115
+ });
116
+ exports.rmSync = function (path) {
117
+ let files = [];
118
+ if (fs.existsSync(path)) {
119
+ files = fs.readdirSync(path);
120
+ for (const [, file] of files.entries()) {
121
+ const curPath = path + "/" + file;
122
+ if (fs.lstatSync(curPath).isDirectory()) {
123
+ // recurse
124
+ exports.rmSync(curPath);
125
+ }
126
+ else {
127
+ // delete file
128
+ fs.unlinkSync(curPath);
129
+ }
130
+ }
131
+ fs.rmdirSync(path);
132
+ }
133
+ };
134
+ exports.checkIfDirectoryExists = (path) => {
135
+ const fs = require("fs");
136
+ if (fs.existsSync(path)) {
137
+ return true;
138
+ }
139
+ return false;
140
+ };
141
+ exports.default = { download: exports.download, decompress: exports.decompress, downloadEditor: exports.downloadEditor, clone: exports.clone, rmSync: exports.rmSync };
@@ -0,0 +1,3 @@
1
+ import { IGitpod } from '../models/gitpod-data';
2
+ declare const Gitpod: IGitpod;
3
+ export default Gitpod;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const console_1 = require("../utils/console");
4
+ const shell = require("shelljs");
5
+ const socket_1 = require("./socket");
6
+ const fs = require("fs");
7
+ const Gitpod = {
8
+ socket: null,
9
+ config: null,
10
+ initialized: false,
11
+ hasGPCommand: false,
12
+ init: function (config) {
13
+ if (this.initialized) {
14
+ return;
15
+ }
16
+ this.initialized = true;
17
+ if (config) {
18
+ this.config = config;
19
+ }
20
+ if (shell.exec('gp -h', { silent: true }).code === 0) {
21
+ this.hasGPCommand = true;
22
+ if (config) {
23
+ config.address = shell
24
+ .exec('gp url', { silent: true })
25
+ .stdout.replace(/(\r\n|\n|\r)/gm, '');
26
+ }
27
+ }
28
+ else {
29
+ console_1.default.debug('Gitpod command line tool not found');
30
+ }
31
+ },
32
+ openFiles: async function (files) {
33
+ var _a;
34
+ console_1.default.debug('Attempting to open files in gitpod mode', files);
35
+ this.init(); // initilize gitpod config
36
+ // gitpod will open files only on isolated mode
37
+ if (!this.config || ((_a = this.config.config) === null || _a === void 0 ? void 0 : _a.grading) !== 'isolated') {
38
+ console_1.default.debug('Files cannot be automatically opened because we are not on isolated grading (only for isolated)');
39
+ socket_1.default.log('ready', ['Ready to compile or test...']);
40
+ return true;
41
+ }
42
+ if (this.hasGPCommand)
43
+ for (const f of files.reverse()) {
44
+ if (shell.exec(`gp open ${f}`).code > 0) {
45
+ console_1.default.debug(`Error opening file ${f} on gitpod`);
46
+ }
47
+ }
48
+ socket_1.default.log('ready', ['Ready to compile or test...']);
49
+ },
50
+ setup(config) {
51
+ this.init(config); // initilize gitpod config
52
+ this.autosave('on');
53
+ },
54
+ autosave: async function (value = 'on') {
55
+ this.init(); // initilize gitpod config
56
+ if (this.hasGPCommand) {
57
+ if (!fs.existsSync('./.theia'))
58
+ fs.mkdirSync('./.theia');
59
+ if (!fs.existsSync('./.theia/settings.json')) {
60
+ fs.writeFileSync('./.theia/settings.json', JSON.stringify({
61
+ 'editor.autoSave': value,
62
+ }, null, 4));
63
+ }
64
+ }
65
+ },
66
+ };
67
+ exports.default = Gitpod;
@@ -0,0 +1,6 @@
1
+ /// <reference types="node" />
2
+ import * as http from "http";
3
+ import { IConfigObj } from "../../models/config";
4
+ import { IConfigManager } from "../../models/config-manager";
5
+ export declare let TEST_SERVER: http.Server;
6
+ export default function (configObj: IConfigObj, configManager: IConfigManager, isTestingEnvironment?: boolean): Promise<any>;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TEST_SERVER = void 0;
4
+ const express = require("express");
5
+ // eslint-disable-next-line
6
+ const cors = require("cors");
7
+ const console_1 = require("../../utils/console");
8
+ const routes_1 = require("./routes");
9
+ const cli_ux_1 = require("cli-ux");
10
+ async function default_1(configObj, configManager, isTestingEnvironment = false) {
11
+ const { config } = configObj;
12
+ const app = express();
13
+ let server;
14
+ if (isTestingEnvironment) {
15
+ if (exports.TEST_SERVER === undefined)
16
+ exports.TEST_SERVER = require("http").Server(app);
17
+ server = exports.TEST_SERVER;
18
+ }
19
+ else
20
+ server = require("http").Server(app);
21
+ app.use(cors());
22
+ // app.use(function(req, res, next) {
23
+ // res.header("Access-Control-Allow-Origin", "*")
24
+ // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
25
+ // res.header("Access-Control-Allow-Methods", "GET,PUT")
26
+ // next()
27
+ // })
28
+ // add all needed endpoints
29
+ await routes_1.default(app, configObj, configManager);
30
+ server.listen(isTestingEnvironment ? 5000 : config === null || config === void 0 ? void 0 : config.port, function () {
31
+ if (!isTestingEnvironment) {
32
+ console_1.default.success(`Exercises are running 😃 Open your browser to start practicing!`);
33
+ console_1.default.success(`\n Open the exercise on this link:`);
34
+ console_1.default.log(` ${config === null || config === void 0 ? void 0 : config.publicUrl}`);
35
+ if ((config === null || config === void 0 ? void 0 : config.editor.mode) === "standalone")
36
+ cli_ux_1.default.open(`${config.publicUrl}`);
37
+ }
38
+ });
39
+ const sockets = new Set();
40
+ server.on("connection", (socket) => {
41
+ sockets.add(socket);
42
+ server.once("close", () => {
43
+ sockets.delete(socket);
44
+ });
45
+ });
46
+ /**
47
+ * Forcefully terminates HTTP server.
48
+ */
49
+ server.terminate = (callback) => {
50
+ for (const socket of sockets) {
51
+ socket.destroy();
52
+ sockets.delete(socket);
53
+ }
54
+ server.close(callback);
55
+ };
56
+ return server;
57
+ }
58
+ exports.default = default_1;
@@ -0,0 +1,4 @@
1
+ import * as express from "express";
2
+ import { IConfigObj } from "../../models/config";
3
+ import { IConfigManager } from "../../models/config-manager";
4
+ export default function (app: express.Application, configObject: IConfigObj, configManager: IConfigManager): Promise<void>;
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const console_1 = require("../../utils/console");
4
+ const express = require("express");
5
+ const fs = require("fs");
6
+ const bodyParser = require("body-parser");
7
+ const socket_1 = require("../socket");
8
+ const fileQueue_1 = require("../../utils/fileQueue");
9
+ // import gitpod from '../gitpod'
10
+ const exercise_1 = require("../config/exercise");
11
+ const session_1 = require("../../managers/session");
12
+ const withHandler = (func) => (req, res) => {
13
+ try {
14
+ func(req, res);
15
+ }
16
+ catch (error) {
17
+ console_1.default.debug(error);
18
+ const _err = {
19
+ message: error.message || "There has been an error",
20
+ status: error.status || 500,
21
+ type: error.type || null,
22
+ };
23
+ console_1.default.error(_err.message);
24
+ // send rep to the server
25
+ res.status(_err.status);
26
+ res.json(_err);
27
+ }
28
+ };
29
+ async function default_1(app, configObject, configManager) {
30
+ const { config, exercises } = configObject;
31
+ const session = await session_1.default.get(configManager === null || configManager === void 0 ? void 0 : configManager.get());
32
+ const dispatcher = fileQueue_1.default.dispatcher({
33
+ create: true,
34
+ path: `${config === null || config === void 0 ? void 0 : config.dirPath}/vscode_queue.json`,
35
+ });
36
+ app.get("/config", withHandler((_, res) => {
37
+ res.json(configObject);
38
+ }));
39
+ // Added this line to parse the json body
40
+ const jsonBodyParser = bodyParser.json();
41
+ // Trying to log in from frontend
42
+ app.post("/login", jsonBodyParser, withHandler(async (req, res) => {
43
+ const email = req.body.email;
44
+ const password = req.body.password;
45
+ session_1.default.destroy();
46
+ const payload = await session_1.default.loginWeb(email, password);
47
+ res.json(payload);
48
+ }));
49
+ app.post("/set-openai-token", jsonBodyParser, withHandler(async (req, res) => {
50
+ const token = req.body.token;
51
+ console.log("Setting openai token");
52
+ const tokenSaved = await session_1.default.setOpenAIToken(token);
53
+ if (tokenSaved) {
54
+ res.json({ status: "ok" });
55
+ }
56
+ else {
57
+ res.status(400);
58
+ }
59
+ }));
60
+ app.get("/check/rigo/status", withHandler(async (_, res) => {
61
+ const payload = await session_1.default.getPayload();
62
+ const openaiToken = await session_1.default.getOpenAIToken();
63
+ // console.log("Looking Rigo creds");
64
+ if (payload && payload.rigobot && payload.rigobot.key) {
65
+ res.json({ rigoToken: payload.rigobot.key });
66
+ }
67
+ else if (openaiToken) {
68
+ res.json({ openaiToken });
69
+ }
70
+ else {
71
+ res
72
+ .status(400)
73
+ .json({ details: `Rigobot token not found, please log in first!` });
74
+ }
75
+ }));
76
+ // symbolic link to maintain path compatiblity
77
+ const fetchStaticAsset = withHandler((req, res) => {
78
+ const filePath = `${config === null || config === void 0 ? void 0 : config.dirPath}/assets/${req.params.filePath}`;
79
+ if (!fs.existsSync(filePath))
80
+ throw new Error("File not found: " + filePath);
81
+ const content = fs.readFileSync(filePath);
82
+ res.write(content);
83
+ res.end();
84
+ });
85
+ app.get(`${(config === null || config === void 0 ? void 0 : config.dirPath.indexOf("./")) === 0 ?
86
+ config.dirPath.slice(1) : config === null || config === void 0 ? void 0 : config.dirPath}/assets/:filePath`, fetchStaticAsset);
87
+ app.get("/assets/:filePath", fetchStaticAsset);
88
+ app.get("/exercise", withHandler((_, res) => {
89
+ res.json(exercises);
90
+ }));
91
+ app.get("/exercise/:slug/readme", withHandler(({ params: { slug }, query: { lang } }, res) => {
92
+ const exercise = configManager.getExercise(slug);
93
+ if (exercise && exercise.getReadme) {
94
+ const readme = exercise.getReadme(lang || null);
95
+ res.json(readme);
96
+ }
97
+ else {
98
+ res.status(400);
99
+ }
100
+ }));
101
+ app.get("/exercise/:slug/report", withHandler(({ params: { slug } }, res) => {
102
+ const exercise = configManager.getExercise(slug);
103
+ if (exercise && exercise.getTestReport) {
104
+ const report = exercise.getTestReport();
105
+ res.json(JSON.stringify(report));
106
+ }
107
+ }));
108
+ app.get("/exercise/:slug", withHandler((req, res) => {
109
+ var _a, _b, _c, _d;
110
+ // no need to re-start exercise if it's already started
111
+ if (configObject.currentExercise &&
112
+ req.params.slug === configObject.currentExercise) {
113
+ const exercise = configManager.getExercise(req.params.slug);
114
+ res.json(exercise);
115
+ return;
116
+ }
117
+ const exercise = configManager.startExercise(req.params.slug);
118
+ dispatcher.enqueue(dispatcher.events.START_EXERCISE, req.params.slug);
119
+ const entries = new Set(Object.keys(config === null || config === void 0 ? void 0 : config.entries).map(lang => config === null || config === void 0 ? void 0 : config.entries[lang]));
120
+ // if we are in incremental grading, the entry file can by dinamically detected
121
+ // based on the changes the student is making during the exercise
122
+ if ((config === null || config === void 0 ? void 0 : config.grading) === "incremental") {
123
+ const scanedFiles = fs.readdirSync("./");
124
+ // update the file hierarchy with updates
125
+ exercise.files = [
126
+ ...exercise.files.filter(f => f.name.includes("test.")),
127
+ ...exercise_1.filterFiles(scanedFiles),
128
+ ];
129
+ console_1.default.debug(`Exercise updated files: `, exercise.files);
130
+ }
131
+ const detected = exercise_1.detect(configObject, exercise.files
132
+ .filter(fileName => entries.has(fileName.name))
133
+ .map(f => f.name || f));
134
+ // if a new language for the testing engine is detected, we replace it
135
+ // if not we leave it as it was before
136
+ if ((config === null || config === void 0 ? void 0 : config.language) && !["", "auto"].includes(config === null || config === void 0 ? void 0 : config.language)) {
137
+ console_1.default.debug(`Exercise language ignored, instead imported from configuration ${config === null || config === void 0 ? void 0 : config.language}`);
138
+ exercise.language = detected === null || detected === void 0 ? void 0 : detected.language;
139
+ }
140
+ else if ((detected === null || detected === void 0 ? void 0 : detected.language) &&
141
+ (!(config === null || config === void 0 ? void 0 : config.language) || (config === null || config === void 0 ? void 0 : config.language) === "auto")) {
142
+ console_1.default.debug(`Switching to ${detected.language} engine in this exercise`);
143
+ exercise.language = detected.language;
144
+ }
145
+ // WARNING: has to be the FULL PATH to the entry path
146
+ // We need to detect entry in both gradings: Incremental and Isolate
147
+ exercise.entry = detected === null || detected === void 0 ? void 0 : detected.entry;
148
+ console_1.default.debug(`Exercise detected entry: ${detected === null || detected === void 0 ? void 0 : detected.entry} and language ${exercise.language}`);
149
+ // exercises.graded and exercises.disableGrading deprecated.
150
+ if (!exercise.graded || (config === null || config === void 0 ? void 0 : config.disableGrading) || ((_a = config === null || config === void 0 ? void 0 : config.disabledActions) === null || _a === void 0 ? void 0 : _a.includes("test"))) {
151
+ socket_1.default.removeAllowed("test");
152
+ }
153
+ else {
154
+ socket_1.default.addAllowed("test");
155
+ }
156
+ if (!exercise.entry || ((_b = config === null || config === void 0 ? void 0 : config.disabledActions) === null || _b === void 0 ? void 0 : _b.includes("build"))) {
157
+ socket_1.default.removeAllowed("build");
158
+ }
159
+ else {
160
+ socket_1.default.addAllowed("build");
161
+ }
162
+ if (exercise.files.filter((f) => !f.name.toLowerCase().includes("readme.") &&
163
+ !f.name.toLowerCase().includes("test.")).length === 0 || ((_c = config === null || config === void 0 ? void 0 : config.disabledActions) === null || _c === void 0 ? void 0 : _c.includes("reset"))) {
164
+ socket_1.default.removeAllowed("reset");
165
+ }
166
+ else if (!((_d = config === null || config === void 0 ? void 0 : config.disabledActions) === null || _d === void 0 ? void 0 : _d.includes("reset"))) {
167
+ socket_1.default.addAllowed("reset");
168
+ }
169
+ socket_1.default.log("ready");
170
+ res.json(exercise);
171
+ }));
172
+ app.get("/exercise/:slug/file/:fileName", withHandler((req, res) => {
173
+ const exercise = configManager.getExercise(req.params.slug);
174
+ if (exercise && exercise.getFile) {
175
+ res.write(exercise.getFile(req.params.fileName));
176
+ res.end();
177
+ }
178
+ }));
179
+ /*
180
+ app.post(
181
+ "/exercise/:slug/file/:fileName",
182
+ withHandler((req: express.Request, res: express.Response) => {
183
+ get tokens but also, add allowed action for 'generate'
184
+ use the sessionManager to keep compatibility with the cli login command.
185
+ })
186
+ );
187
+ */
188
+ const textBodyParser = bodyParser.text();
189
+ app.put("/exercise/:slug/file/:fileName", textBodyParser, withHandler((req, res) => {
190
+ const exercise = configManager.getExercise(req.params.slug);
191
+ if (exercise && exercise.saveFile) {
192
+ exercise.saveFile(req.params.fileName, req.body);
193
+ res.end();
194
+ }
195
+ }));
196
+ if (config === null || config === void 0 ? void 0 : config.outputPath) {
197
+ app.use("/preview", express.static(config.outputPath));
198
+ }
199
+ app.use("/", express.static(`${config === null || config === void 0 ? void 0 : config.dirPath}/_app`));
200
+ }
201
+ exports.default = default_1;
@@ -0,0 +1,3 @@
1
+ import { ISession } from "../models/session";
2
+ declare const Session: ISession;
3
+ export default Session;
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const console_1 = require("../utils/console");
4
+ const api_1 = require("../utils/api");
5
+ const validator_1 = require("validator");
6
+ const errors_1 = require("../utils/errors");
7
+ const fs = require("fs");
8
+ const cli_ux_1 = require("cli-ux");
9
+ const storage = require("node-persist");
10
+ const Session = {
11
+ sessionStarted: false,
12
+ token: null,
13
+ config: null,
14
+ currentCohort: null,
15
+ initialize: async function () {
16
+ if (!this.sessionStarted) {
17
+ if (!this.config) {
18
+ throw errors_1.InternalError("Configuration not found");
19
+ }
20
+ if (!fs.existsSync(this.config.dirPath)) {
21
+ fs.mkdirSync(this.config.dirPath);
22
+ }
23
+ await storage.init({ dir: `${this.config.dirPath}/.session` });
24
+ this.sessionStarted = true;
25
+ }
26
+ return true;
27
+ },
28
+ getOpenAIToken: async function () {
29
+ await this.initialize();
30
+ let token = null;
31
+ try {
32
+ token = await storage.getItem("openai-token");
33
+ }
34
+ catch (_a) {
35
+ console_1.default.debug("Error retriving openai token");
36
+ }
37
+ return token;
38
+ },
39
+ setOpenAIToken: async function (token) {
40
+ await this.initialize();
41
+ await storage.setItem("openai-token", token);
42
+ console_1.default.debug("OpenAI token successfuly set");
43
+ return true;
44
+ },
45
+ setPayload: async function (value) {
46
+ await this.initialize();
47
+ await storage.setItem("bc-payload", Object.assign({ token: this.token }, value));
48
+ console_1.default.debug("Payload successfuly found and set for " + value.email);
49
+ return true;
50
+ },
51
+ getPayload: async function () {
52
+ await this.initialize();
53
+ let payload = null;
54
+ try {
55
+ payload = await storage.getItem("bc-payload");
56
+ }
57
+ catch (error) {
58
+ // TODO: Remove it
59
+ console.log(error);
60
+ console_1.default.debug("Error retriving session payload");
61
+ }
62
+ return payload;
63
+ },
64
+ isActive: function () {
65
+ /* if (this.token) {
66
+ return true
67
+ } else {
68
+ return false
69
+ } */
70
+ return !!this.token;
71
+ },
72
+ get: async function (configObj) {
73
+ if (configObj && configObj.config) {
74
+ this.config = configObj.config;
75
+ }
76
+ await this.sync();
77
+ if (!this.isActive()) {
78
+ return null;
79
+ }
80
+ const payload = await this.getPayload();
81
+ return {
82
+ payload,
83
+ token: this.token,
84
+ };
85
+ },
86
+ login: async function () {
87
+ const email = await cli_ux_1.default.prompt("What is your email?");
88
+ if (!validator_1.default.isEmail(email)) {
89
+ throw errors_1.ValidationError("Invalid email");
90
+ }
91
+ const password = await cli_ux_1.default.prompt("What is your password?", {
92
+ type: "hide",
93
+ });
94
+ const data = await api_1.default.login(email, password);
95
+ if (data) {
96
+ cli_ux_1.default.log(data);
97
+ this.start({ token: data.token, payload: data });
98
+ }
99
+ },
100
+ loginWeb: async function (email, password) {
101
+ if (!validator_1.default.isEmail(email)) {
102
+ throw errors_1.ValidationError("Invalid email");
103
+ }
104
+ const data = await api_1.default.login(email, password);
105
+ if (data) {
106
+ this.start({ token: data.token, payload: data });
107
+ return data;
108
+ }
109
+ },
110
+ sync: async function () {
111
+ const payload = await this.getPayload();
112
+ if (payload) {
113
+ this.token = payload.token;
114
+ }
115
+ },
116
+ start: async function ({ token, payload = null }) {
117
+ if (!token) {
118
+ throw new Error("A token and email is needed to start a session");
119
+ }
120
+ this.token = token;
121
+ if (payload && (await this.setPayload(payload))) {
122
+ console_1.default.success(`Successfully logged in as ${payload.email}`);
123
+ }
124
+ },
125
+ destroy: async function () {
126
+ await storage.clear();
127
+ this.token = null;
128
+ console_1.default.success("You have logged out");
129
+ },
130
+ };
131
+ exports.default = Session;
@@ -0,0 +1,3 @@
1
+ import { ISocket } from "../models/socket";
2
+ declare const SocketManager: ISocket;
3
+ export default SocketManager;