@learnpack/learnpack 2.1.3 → 2.1.6

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -21,7 +21,7 @@ $ npm install -g @learnpack/learnpack
21
21
  $ learnpack COMMAND
22
22
  running command...
23
23
  $ learnpack (-v|--version|version)
24
- @learnpack/learnpack/2.1.3 win32-x64 node-v16.14.0
24
+ @learnpack/learnpack/2.1.6 win32-x64 node-v16.14.0
25
25
  $ learnpack --help [COMMAND]
26
26
  USAGE
27
27
  $ learnpack COMMAND
@@ -74,7 +74,7 @@ DESCRIPTION
74
74
  12. If there is a file within the exercises folder but not inside of any particular exercise's folder. (Warning)
75
75
  ```
76
76
 
77
- _See code: [src\commands\audit.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\audit.ts)_
77
+ _See code: [src\commands\audit.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\audit.ts)_
78
78
 
79
79
  ## `learnpack clean`
80
80
 
@@ -89,7 +89,7 @@ DESCRIPTION
89
89
  Extra documentation goes here
90
90
  ```
91
91
 
92
- _See code: [src\commands\clean.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\clean.ts)_
92
+ _See code: [src\commands\clean.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\clean.ts)_
93
93
 
94
94
  ## `learnpack download [PACKAGE]`
95
95
 
@@ -107,7 +107,7 @@ DESCRIPTION
107
107
  Extra documentation goes here
108
108
  ```
109
109
 
110
- _See code: [src\commands\download.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\download.ts)_
110
+ _See code: [src\commands\download.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\download.ts)_
111
111
 
112
112
  ## `learnpack help [COMMAND]`
113
113
 
@@ -138,7 +138,7 @@ OPTIONS
138
138
  -h, --grading show CLI help
139
139
  ```
140
140
 
141
- _See code: [src\commands\init.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\init.ts)_
141
+ _See code: [src\commands\init.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\init.ts)_
142
142
 
143
143
  ## `learnpack login [PACKAGE]`
144
144
 
@@ -156,7 +156,7 @@ DESCRIPTION
156
156
  Extra documentation goes here
157
157
  ```
158
158
 
159
- _See code: [src\commands\login.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\login.ts)_
159
+ _See code: [src\commands\login.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\login.ts)_
160
160
 
161
161
  ## `learnpack logout [PACKAGE]`
162
162
 
@@ -174,7 +174,7 @@ DESCRIPTION
174
174
  Extra documentation goes here
175
175
  ```
176
176
 
177
- _See code: [src\commands\logout.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\logout.ts)_
177
+ _See code: [src\commands\logout.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\logout.ts)_
178
178
 
179
179
  ## `learnpack plugins`
180
180
 
@@ -309,7 +309,7 @@ DESCRIPTION
309
309
  Extra documentation goes here
310
310
  ```
311
311
 
312
- _See code: [src\commands\publish.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\publish.ts)_
312
+ _See code: [src\commands\publish.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\publish.ts)_
313
313
 
314
314
  ## `learnpack start`
315
315
 
@@ -330,7 +330,7 @@ OPTIONS
330
330
  -w, --watch Watch for file changes
331
331
  ```
332
332
 
333
- _See code: [src\commands\start.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\start.ts)_
333
+ _See code: [src\commands\start.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\start.ts)_
334
334
 
335
335
  ## `learnpack test [EXERCISESLUG]`
336
336
 
@@ -344,5 +344,5 @@ ARGUMENTS
344
344
  EXERCISESLUG The name of the exercise to test
345
345
  ```
346
346
 
347
- _See code: [src\commands\test.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.3/src\commands\test.ts)_
347
+ _See code: [src\commands\test.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.6/src\commands\test.ts)_
348
348
  <!-- commandsstop -->
@@ -38,10 +38,8 @@ class AuditCommand extends SessionCommand_1.default {
38
38
  // Checks if learnpack clean has been run
39
39
  audit_1.default.checkLearnpackClean(config, errors);
40
40
  // Build exercises if they are not built yet.
41
- if (!config.exercises || config.exercises.length === 0) {
42
- (_b = this.configManager) === null || _b === void 0 ? void 0 : _b.buildIndex();
43
- config = (_c = this.configManager) === null || _c === void 0 ? void 0 : _c.get();
44
- }
41
+ (_b = this.configManager) === null || _b === void 0 ? void 0 : _b.buildIndex();
42
+ config = (_c = this.configManager) === null || _c === void 0 ? void 0 : _c.get();
45
43
  // Check if the exercises folder has some files within any ./exercise
46
44
  const exercisesPath = config.config.exercisesPath;
47
45
  fs.readdir(exercisesPath, (err, files) => {
@@ -175,8 +173,8 @@ class AuditCommand extends SessionCommand_1.default {
175
173
  try {
176
174
  // eslint-disable-next-line
177
175
  let res = await fetch(obj[link].mdUrl, { method: "HEAD" });
178
- console_1.default.log("Response links:", obj[link].mdUrl, res);
179
176
  if (res.status > 399 && res.status < 500) {
177
+ console_1.default.log("Response links:", res.status, obj[link].mdUrl, res);
180
178
  counter.links.error++;
181
179
  errors.push({
182
180
  exercise: exercise.title,
@@ -86,6 +86,7 @@ exports.default = async ({ grading, mode, disableGrading, version, }) => {
86
86
  [] }));
87
87
  // auto detect agent (if possible)
88
88
  if (shell.which("gp") && configObj && configObj.config) {
89
+ configObj.config.editor.agent = "vscode";
89
90
  configObj.address = getGitpodAddress();
90
91
  configObj.config.publicUrl = `https://${configObj.config.port}-${(_b = configObj.address) === null || _b === void 0 ? void 0 : _b.slice(8)}`;
91
92
  }
@@ -64,9 +64,9 @@ async function default_1(app, configObject, configManager) {
64
64
  res.json(exercises);
65
65
  }));
66
66
  app.get("/exercise/:slug/readme", withHandler(({ params: { slug }, query: { lang } }, res) => {
67
- const excercise = configManager.getExercise(slug);
68
- if (excercise) {
69
- const readme = excercise.getReadme(lang || null);
67
+ const exercise = configManager.getExercise(slug);
68
+ if (exercise && exercise.getReadme) {
69
+ const readme = exercise.getReadme(lang || null);
70
70
  res.json(readme);
71
71
  }
72
72
  else {
@@ -74,8 +74,11 @@ async function default_1(app, configObject, configManager) {
74
74
  }
75
75
  }));
76
76
  app.get("/exercise/:slug/report", withHandler(({ params: { slug } }, res) => {
77
- const report = configManager.getExercise(slug).getTestReport();
78
- res.json(JSON.stringify(report));
77
+ const exercise = configManager.getExercise(slug);
78
+ if (exercise && exercise.getTestReport) {
79
+ const report = exercise.getTestReport();
80
+ res.json(JSON.stringify(report));
81
+ }
79
82
  }));
80
83
  app.get("/exercise/:slug", withHandler((req, res) => {
81
84
  var _a, _b, _c, _d;
@@ -141,16 +144,19 @@ async function default_1(app, configObject, configManager) {
141
144
  res.json(exercise);
142
145
  }));
143
146
  app.get("/exercise/:slug/file/:fileName", withHandler((req, res) => {
144
- res.write(configManager.getExercise(req.params.slug).getFile(req.params.fileName));
145
- res.end();
147
+ const exercise = configManager.getExercise(req.params.slug);
148
+ if (exercise && exercise.getFile) {
149
+ res.write(exercise.getFile(req.params.fileName));
150
+ res.end();
151
+ }
146
152
  }));
147
153
  const textBodyParser = bodyParser.text();
148
154
  app.put("/exercise/:slug/file/:fileName", textBodyParser, withHandler((req, res) => {
149
- // const result =
150
- configManager
151
- .getExercise(req.params.slug)
152
- .saveFile(req.params.fileName, req.body);
153
- res.end();
155
+ const exercise = configManager.getExercise(req.params.slug);
156
+ if (exercise && exercise.saveFile) {
157
+ exercise.saveFile(req.params.fileName, req.body);
158
+ res.end();
159
+ }
154
160
  }));
155
161
  if (config === null || config === void 0 ? void 0 : config.outputPath) {
156
162
  app.use("/preview", express.static(config.outputPath));
@@ -15,10 +15,10 @@ export interface IExercise {
15
15
  [key: string]: string;
16
16
  };
17
17
  title: string;
18
- getReadme: (lang: string | null) => any;
19
- getFile: (name: string) => string | Buffer;
20
- saveFile: (name: string, content: string) => void;
21
- getTestReport: () => any;
18
+ getReadme?: (lang: string | null) => any;
19
+ getFile?: (name: string) => string | Buffer;
20
+ saveFile?: (name: string, content: string) => void;
21
+ getTestReport?: () => any;
22
22
  test?: (sessionConfig: any, config: IConfig, socket: ISocket) => void;
23
23
  }
24
24
  export interface IExerciseData {
@@ -1 +1 @@
1
- {"version":"2.1.3","commands":{"audit":{"id":"audit","description":"learnpack audit is the command in charge of creating an auditory of the repository\n...\nlearnpack audit checks for the following information in a repository:\n 1. The configuration object has slug, repository and description. (Error)\n 2. The command learnpack clean has been run. (Error)\n 3. If a markdown or test file doesn't have any content. (Error)\n 4. The links are accessing to valid servers. (Error)\n 5. The relative images are working (If they have the shortest path to the image or if the images exists in the assets). (Error)\n 6. The external images are working (If they are pointing to a valid server). (Error)\n 7. The exercises directory names are valid. (Error)\n 8. If an exercise doesn't have a README file. (Error)\n 9. The exercises array (Of the config file) has content. (Error)\n 10. The exercses have the same translations. (Warning)\n 11. The .gitignore file exists. (Warning)\n 12. If there is a file within the exercises folder but not inside of any particular exercise's folder. (Warning)\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"clean":{"id":"clean","description":"Clean the configuration object\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"download":{"id":"download","description":"Describe the command here\n...\nExtra documentation goes here\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"init":{"id":"init","description":"Create a new learning package: Book, Tutorial or Exercise","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"grading":{"name":"grading","type":"boolean","char":"h","description":"show CLI help","allowNo":false}},"args":[]},"login":{"id":"login","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"logout":{"id":"logout","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"publish":{"id":"publish","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"start":{"id":"start","description":"Runs a small server with all the exercise instructions","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"port":{"name":"port","type":"option","char":"p","description":"server port"},"host":{"name":"host","type":"option","char":"h","description":"server host"},"disableGrading":{"name":"disableGrading","type":"boolean","char":"D","description":"disble grading functionality","allowNo":false},"watch":{"name":"watch","type":"boolean","char":"w","description":"Watch for file changes","allowNo":false},"editor":{"name":"editor","type":"option","char":"e","description":"[standalone, gitpod]","options":["standalone","gitpod"]},"version":{"name":"version","type":"option","char":"v","description":"E.g: 1.0.1"},"grading":{"name":"grading","type":"option","char":"g","description":"[isolated, incremental]","options":["isolated","incremental"]},"debug":{"name":"debug","type":"boolean","char":"d","description":"debugger mode for more verbage","allowNo":false}},"args":[]},"test":{"id":"test","description":"Test exercises","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"exerciseSlug","description":"The name of the exercise to test","required":false,"hidden":false}]}}}
1
+ {"version":"2.1.6","commands":{"audit":{"id":"audit","description":"learnpack audit is the command in charge of creating an auditory of the repository\n...\nlearnpack audit checks for the following information in a repository:\n 1. The configuration object has slug, repository and description. (Error)\n 2. The command learnpack clean has been run. (Error)\n 3. If a markdown or test file doesn't have any content. (Error)\n 4. The links are accessing to valid servers. (Error)\n 5. The relative images are working (If they have the shortest path to the image or if the images exists in the assets). (Error)\n 6. The external images are working (If they are pointing to a valid server). (Error)\n 7. The exercises directory names are valid. (Error)\n 8. If an exercise doesn't have a README file. (Error)\n 9. The exercises array (Of the config file) has content. (Error)\n 10. The exercses have the same translations. (Warning)\n 11. The .gitignore file exists. (Warning)\n 12. If there is a file within the exercises folder but not inside of any particular exercise's folder. (Warning)\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"clean":{"id":"clean","description":"Clean the configuration object\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"download":{"id":"download","description":"Describe the command here\n...\nExtra documentation goes here\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"init":{"id":"init","description":"Create a new learning package: Book, Tutorial or Exercise","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"grading":{"name":"grading","type":"boolean","char":"h","description":"show CLI help","allowNo":false}},"args":[]},"login":{"id":"login","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"logout":{"id":"logout","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"publish":{"id":"publish","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"start":{"id":"start","description":"Runs a small server with all the exercise instructions","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"port":{"name":"port","type":"option","char":"p","description":"server port"},"host":{"name":"host","type":"option","char":"h","description":"server host"},"disableGrading":{"name":"disableGrading","type":"boolean","char":"D","description":"disble grading functionality","allowNo":false},"watch":{"name":"watch","type":"boolean","char":"w","description":"Watch for file changes","allowNo":false},"editor":{"name":"editor","type":"option","char":"e","description":"[standalone, gitpod]","options":["standalone","gitpod"]},"version":{"name":"version","type":"option","char":"v","description":"E.g: 1.0.1"},"grading":{"name":"grading","type":"option","char":"g","description":"[isolated, incremental]","options":["isolated","incremental"]},"debug":{"name":"debug","type":"boolean","char":"d","description":"debugger mode for more verbage","allowNo":false}},"args":[]},"test":{"id":"test","description":"Test exercises","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"exerciseSlug","description":"The name of the exercise to test","required":false,"hidden":false}]}}}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@learnpack/learnpack",
3
3
  "description": "Create, sell or download and take learning amazing learning packages",
4
- "version": "2.1.3",
4
+ "version": "2.1.6",
5
5
  "author": "Alejandro Sanchez @alesanchezr",
6
6
  "bin": {
7
7
  "learnpack": "bin/run"
@@ -48,10 +48,8 @@ class AuditCommand extends SessionCommand {
48
48
  Audit.checkLearnpackClean(config, errors);
49
49
 
50
50
  // Build exercises if they are not built yet.
51
- if (!config.exercises || config.exercises.length === 0) {
52
- this.configManager?.buildIndex();
53
- config = this.configManager?.get();
54
- }
51
+ this.configManager?.buildIndex();
52
+ config = this.configManager?.get();
55
53
 
56
54
  // Check if the exercises folder has some files within any ./exercise
57
55
  const exercisesPath: string = config!.config!.exercisesPath;
@@ -220,8 +218,13 @@ return false;
220
218
  try {
221
219
  // eslint-disable-next-line
222
220
  let res = await fetch(obj[link].mdUrl, { method: "HEAD" });
223
- Console.log("Response links:", obj[link].mdUrl, res);
224
221
  if (res.status > 399 && res.status < 500) {
222
+ Console.log(
223
+ "Response links:",
224
+ res.status,
225
+ obj[link].mdUrl,
226
+ res
227
+ );
225
228
  counter.links.error++;
226
229
  errors.push({
227
230
  exercise: exercise.title,
@@ -125,6 +125,7 @@ export default async ({
125
125
 
126
126
  // auto detect agent (if possible)
127
127
  if (shell.which("gp") && configObj && configObj.config) {
128
+ configObj.config.editor.agent = "vscode";
128
129
  configObj.address = getGitpodAddress();
129
130
  configObj.config.publicUrl = `https://${
130
131
  configObj.config.port
@@ -1,255 +1,259 @@
1
- import Console from "../../utils/console";
2
- import * as express from "express";
3
- import * as fs from "fs";
4
- import * as bodyParser from "body-parser";
5
- import socket from "../socket";
6
- import queue from "../../utils/fileQueue";
7
- // import gitpod from '../gitpod'
8
- import { detect, filterFiles } from "../config/exercise";
9
- import { IFile } from "../../models/file";
10
- import { IConfigObj, TEntries } from "../../models/config";
11
- import { IConfigManager } from "../../models/config-manager";
12
- import { IExercise } from "../../models/exercise-obj";
13
-
14
- const withHandler =
15
- (func: (req: express.Request, res: express.Response) => void) =>
16
- (req: express.Request, res: express.Response) => {
17
- try {
18
- func(req, res);
19
- } catch (error) {
20
- Console.debug(error);
21
- const _err = {
22
- message: (error as TypeError).message || "There has been an error",
23
- status: (error as any).status || 500,
24
- type: (error as any).type || null,
25
- };
26
- Console.error(_err.message);
27
-
28
- // send rep to the server
29
- res.status(_err.status);
30
- res.json(_err);
31
- }
32
- };
33
-
34
- export default async function (
35
- app: express.Application,
36
- configObject: IConfigObj,
37
- configManager: IConfigManager
38
- ) {
39
- const { config, exercises } = configObject;
40
-
41
- const dispatcher = queue.dispatcher({
42
- create: true,
43
- path: `${config?.dirPath}/vscode_queue.json`,
44
- });
45
- app.get(
46
- "/config",
47
- withHandler((_: express.Request, res: express.Response) => {
48
- res.json(configObject);
49
- })
50
- );
51
-
52
- /**
53
- * TODO: replicate a socket action, the request payload must be passed to the socket as well
54
-
55
- const jsonBodyParser = bodyParser.json()
56
-
57
- type ISocketActions = "addAllowed" | "removeAllowed" | "start" | "on" | "clean" | "ask" | "reload" | "openWindow" | "log" | "emit" | "ready" | "error" | "fatal" | "success" | "onTestingFinished";
58
-
59
- app.post('/socket/:actionName', jsonBodyParser, withHandler((req, res) => {
60
- if (socket[req.params.actionName as ISocketActions] instanceof Function) {
61
- socket[req.params.actionName as ISocketActions](req.body ? req.body.data : null)
62
- res.json({ "details": "Socket call executed sucessfully" })
63
- } else res.status(400).json({ "details": `Socket action ${req.params.actionName} not found` })
64
- }))
65
- */
66
-
67
- // symbolic link to maintain path compatiblity
68
- const fetchStaticAsset = withHandler((req, res) => {
69
- const filePath = `${config?.dirPath}/assets/${req.params.filePath}`;
70
- if (!fs.existsSync(filePath))
71
- throw new Error("File not found: " + filePath);
72
- const content = fs.readFileSync(filePath);
73
- res.write(content);
74
- res.end();
75
- });
76
-
77
- app.get(
78
- `${
79
- config?.dirPath.indexOf("./") === 0 ?
80
- config.dirPath.slice(1) :
81
- config?.dirPath
82
- }/assets/:filePath`,
83
- fetchStaticAsset
84
- );
85
-
86
- app.get("/assets/:filePath", fetchStaticAsset);
87
-
88
- app.get(
89
- "/exercise",
90
- withHandler((_: express.Request, res: express.Response) => {
91
- res.json(exercises);
92
- })
93
- );
94
-
95
- app.get(
96
- "/exercise/:slug/readme",
97
- withHandler(
98
- (
99
- { params: { slug }, query: { lang } }: express.Request,
100
- res: express.Response
101
- ) => {
102
- const excercise: IExercise = configManager.getExercise(slug);
103
-
104
- if (excercise) {
105
- const readme = excercise.getReadme((lang as string) || null);
106
- res.json(readme);
107
- } else {
108
- res.status(400);
109
- }
110
- }
111
- )
112
- );
113
-
114
- app.get(
115
- "/exercise/:slug/report",
116
- withHandler(
117
- ({ params: { slug } }: express.Request, res: express.Response) => {
118
- const report = configManager.getExercise(slug).getTestReport();
119
- res.json(JSON.stringify(report));
120
- }
121
- )
122
- );
123
-
124
- app.get(
125
- "/exercise/:slug",
126
- withHandler((req: express.Request, res: express.Response) => {
127
- // no need to re-start exercise if it's already started
128
- if (
129
- configObject.currentExercise &&
130
- req.params.slug === configObject.currentExercise
131
- ) {
132
- const exercise = configManager.getExercise(req.params.slug);
133
- res.json(exercise);
134
- return;
135
- }
136
-
137
- const exercise = configManager.startExercise(req.params.slug);
138
- dispatcher.enqueue(dispatcher.events.START_EXERCISE, req.params.slug);
139
-
140
- type TEntry = "python3" | "html" | "node" | "react" | "java";
141
-
142
- const entries = new Set(
143
- Object.keys(config?.entries!).map(
144
- lang => config?.entries[lang as TEntry]
145
- )
146
- );
147
-
148
- // if we are in incremental grading, the entry file can by dinamically detected
149
- // based on the changes the student is making during the exercise
150
- if (config?.grading === "incremental") {
151
- const scanedFiles = fs.readdirSync("./");
152
-
153
- // update the file hierarchy with updates
154
- exercise.files = [
155
- ...exercise.files.filter(f => f.name.includes("test.")),
156
- ...filterFiles(scanedFiles),
157
- ];
158
- Console.debug(`Exercise updated files: `, exercise.files);
159
- }
160
-
161
- const detected = detect(
162
- configObject,
163
- exercise.files
164
- .filter(fileName => entries.has(fileName.name))
165
- .map(f => f.name || f) as string[]
166
- );
167
-
168
- // if a new language for the testing engine is detected, we replace it
169
- // if not we leave it as it was before
170
- if (config?.language && !["", "auto"].includes(config?.language)) {
171
- Console.debug(
172
- `Exercise language ignored, instead imported from configuration ${config?.language}`
173
- );
174
- exercise.language = detected?.language;
175
- } else if (
176
- detected?.language &&
177
- (!config?.language || config?.language === "auto")
178
- ) {
179
- Console.debug(
180
- `Switching to ${detected.language} engine in this exercise`
181
- );
182
- exercise.language = detected.language;
183
- }
184
-
185
- // WARNING: has to be the FULL PATH to the entry path
186
- // We need to detect entry in both gradings: Incremental and Isolate
187
- exercise.entry = detected?.entry;
188
- Console.debug(
189
- `Exercise detected entry: ${detected?.entry} and language ${exercise.language}`
190
- );
191
-
192
- if (
193
- !exercise.graded ||
194
- config?.disableGrading ||
195
- config?.disabledActions?.includes("test")
196
- ) {
197
- socket.removeAllowed("test");
198
- } else {
199
- socket.addAllowed("test");
200
- }
201
-
202
- if (!exercise.entry || config?.disabledActions?.includes("build")) {
203
- socket.removeAllowed("build");
204
- } else {
205
- socket.addAllowed("build");
206
- }
207
-
208
- if (
209
- exercise.files.filter(
210
- (f: IFile) =>
211
- !f.name.toLowerCase().includes("readme.") &&
212
- !f.name.toLowerCase().includes("test.")
213
- ).length === 0 ||
214
- config?.disabledActions?.includes("reset")
215
- ) {
216
- socket.removeAllowed("reset");
217
- } else if (!config?.disabledActions?.includes("reset")) {
218
- socket.addAllowed("reset");
219
- }
220
-
221
- socket.log("ready");
222
-
223
- res.json(exercise);
224
- })
225
- );
226
-
227
- app.get(
228
- "/exercise/:slug/file/:fileName",
229
- withHandler((req: express.Request, res: express.Response) => {
230
- res.write(
231
- configManager.getExercise(req.params.slug).getFile(req.params.fileName)
232
- );
233
- res.end();
234
- })
235
- );
236
-
237
- const textBodyParser = bodyParser.text();
238
- app.put(
239
- "/exercise/:slug/file/:fileName",
240
- textBodyParser,
241
- withHandler((req: express.Request, res: express.Response) => {
242
- // const result =
243
- configManager
244
- .getExercise(req.params.slug)
245
- .saveFile(req.params.fileName, req.body);
246
- res.end();
247
- })
248
- );
249
-
250
- if (config?.outputPath) {
251
- app.use("/preview", express.static(config.outputPath));
252
- }
253
-
254
- app.use("/", express.static(`${config?.dirPath}/_app`));
255
- }
1
+ import Console from "../../utils/console";
2
+ import * as express from "express";
3
+ import * as fs from "fs";
4
+ import * as bodyParser from "body-parser";
5
+ import socket from "../socket";
6
+ import queue from "../../utils/fileQueue";
7
+ // import gitpod from '../gitpod'
8
+ import { detect, filterFiles } from "../config/exercise";
9
+ import { IFile } from "../../models/file";
10
+ import { IConfigObj, TEntries } from "../../models/config";
11
+ import { IConfigManager } from "../../models/config-manager";
12
+ import { IExercise } from "../../models/exercise-obj";
13
+
14
+ const withHandler =
15
+ (func: (req: express.Request, res: express.Response) => void) =>
16
+ (req: express.Request, res: express.Response) => {
17
+ try {
18
+ func(req, res);
19
+ } catch (error) {
20
+ Console.debug(error);
21
+ const _err = {
22
+ message: (error as TypeError).message || "There has been an error",
23
+ status: (error as any).status || 500,
24
+ type: (error as any).type || null,
25
+ };
26
+ Console.error(_err.message);
27
+
28
+ // send rep to the server
29
+ res.status(_err.status);
30
+ res.json(_err);
31
+ }
32
+ };
33
+
34
+ export default async function (
35
+ app: express.Application,
36
+ configObject: IConfigObj,
37
+ configManager: IConfigManager
38
+ ) {
39
+ const { config, exercises } = configObject;
40
+
41
+ const dispatcher = queue.dispatcher({
42
+ create: true,
43
+ path: `${config?.dirPath}/vscode_queue.json`,
44
+ });
45
+ app.get(
46
+ "/config",
47
+ withHandler((_: express.Request, res: express.Response) => {
48
+ res.json(configObject);
49
+ })
50
+ );
51
+
52
+ /**
53
+ * TODO: replicate a socket action, the request payload must be passed to the socket as well
54
+
55
+ const jsonBodyParser = bodyParser.json()
56
+
57
+ type ISocketActions = "addAllowed" | "removeAllowed" | "start" | "on" | "clean" | "ask" | "reload" | "openWindow" | "log" | "emit" | "ready" | "error" | "fatal" | "success" | "onTestingFinished";
58
+
59
+ app.post('/socket/:actionName', jsonBodyParser, withHandler((req, res) => {
60
+ if (socket[req.params.actionName as ISocketActions] instanceof Function) {
61
+ socket[req.params.actionName as ISocketActions](req.body ? req.body.data : null)
62
+ res.json({ "details": "Socket call executed sucessfully" })
63
+ } else res.status(400).json({ "details": `Socket action ${req.params.actionName} not found` })
64
+ }))
65
+ */
66
+
67
+ // symbolic link to maintain path compatiblity
68
+ const fetchStaticAsset = withHandler((req, res) => {
69
+ const filePath = `${config?.dirPath}/assets/${req.params.filePath}`;
70
+ if (!fs.existsSync(filePath))
71
+ throw new Error("File not found: " + filePath);
72
+ const content = fs.readFileSync(filePath);
73
+ res.write(content);
74
+ res.end();
75
+ });
76
+
77
+ app.get(
78
+ `${
79
+ config?.dirPath.indexOf("./") === 0 ?
80
+ config.dirPath.slice(1) :
81
+ config?.dirPath
82
+ }/assets/:filePath`,
83
+ fetchStaticAsset
84
+ );
85
+
86
+ app.get("/assets/:filePath", fetchStaticAsset);
87
+
88
+ app.get(
89
+ "/exercise",
90
+ withHandler((_: express.Request, res: express.Response) => {
91
+ res.json(exercises);
92
+ })
93
+ );
94
+
95
+ app.get(
96
+ "/exercise/:slug/readme",
97
+ withHandler(
98
+ (
99
+ { params: { slug }, query: { lang } }: express.Request,
100
+ res: express.Response
101
+ ) => {
102
+ const exercise: IExercise = configManager.getExercise(slug);
103
+
104
+ if (exercise && exercise.getReadme) {
105
+ const readme = exercise.getReadme((lang as string) || null);
106
+ res.json(readme);
107
+ } else {
108
+ res.status(400);
109
+ }
110
+ }
111
+ )
112
+ );
113
+
114
+ app.get(
115
+ "/exercise/:slug/report",
116
+ withHandler(
117
+ ({ params: { slug } }: express.Request, res: express.Response) => {
118
+ const exercise = configManager.getExercise(slug);
119
+ if (exercise && exercise.getTestReport) {
120
+ const report = exercise.getTestReport();
121
+ res.json(JSON.stringify(report));
122
+ }
123
+ }
124
+ )
125
+ );
126
+
127
+ app.get(
128
+ "/exercise/:slug",
129
+ withHandler((req: express.Request, res: express.Response) => {
130
+ // no need to re-start exercise if it's already started
131
+ if (
132
+ configObject.currentExercise &&
133
+ req.params.slug === configObject.currentExercise
134
+ ) {
135
+ const exercise = configManager.getExercise(req.params.slug);
136
+ res.json(exercise);
137
+ return;
138
+ }
139
+
140
+ const exercise = configManager.startExercise(req.params.slug);
141
+ dispatcher.enqueue(dispatcher.events.START_EXERCISE, req.params.slug);
142
+
143
+ type TEntry = "python3" | "html" | "node" | "react" | "java";
144
+
145
+ const entries = new Set(
146
+ Object.keys(config?.entries!).map(
147
+ lang => config?.entries[lang as TEntry]
148
+ )
149
+ );
150
+
151
+ // if we are in incremental grading, the entry file can by dinamically detected
152
+ // based on the changes the student is making during the exercise
153
+ if (config?.grading === "incremental") {
154
+ const scanedFiles = fs.readdirSync("./");
155
+
156
+ // update the file hierarchy with updates
157
+ exercise.files = [
158
+ ...exercise.files.filter(f => f.name.includes("test.")),
159
+ ...filterFiles(scanedFiles),
160
+ ];
161
+ Console.debug(`Exercise updated files: `, exercise.files);
162
+ }
163
+
164
+ const detected = detect(
165
+ configObject,
166
+ exercise.files
167
+ .filter(fileName => entries.has(fileName.name))
168
+ .map(f => f.name || f) as string[]
169
+ );
170
+
171
+ // if a new language for the testing engine is detected, we replace it
172
+ // if not we leave it as it was before
173
+ if (config?.language && !["", "auto"].includes(config?.language)) {
174
+ Console.debug(
175
+ `Exercise language ignored, instead imported from configuration ${config?.language}`
176
+ );
177
+ exercise.language = detected?.language;
178
+ } else if (
179
+ detected?.language &&
180
+ (!config?.language || config?.language === "auto")
181
+ ) {
182
+ Console.debug(
183
+ `Switching to ${detected.language} engine in this exercise`
184
+ );
185
+ exercise.language = detected.language;
186
+ }
187
+
188
+ // WARNING: has to be the FULL PATH to the entry path
189
+ // We need to detect entry in both gradings: Incremental and Isolate
190
+ exercise.entry = detected?.entry;
191
+ Console.debug(
192
+ `Exercise detected entry: ${detected?.entry} and language ${exercise.language}`
193
+ );
194
+
195
+ if (
196
+ !exercise.graded ||
197
+ config?.disableGrading ||
198
+ config?.disabledActions?.includes("test")
199
+ ) {
200
+ socket.removeAllowed("test");
201
+ } else {
202
+ socket.addAllowed("test");
203
+ }
204
+
205
+ if (!exercise.entry || config?.disabledActions?.includes("build")) {
206
+ socket.removeAllowed("build");
207
+ } else {
208
+ socket.addAllowed("build");
209
+ }
210
+
211
+ if (
212
+ exercise.files.filter(
213
+ (f: IFile) =>
214
+ !f.name.toLowerCase().includes("readme.") &&
215
+ !f.name.toLowerCase().includes("test.")
216
+ ).length === 0 ||
217
+ config?.disabledActions?.includes("reset")
218
+ ) {
219
+ socket.removeAllowed("reset");
220
+ } else if (!config?.disabledActions?.includes("reset")) {
221
+ socket.addAllowed("reset");
222
+ }
223
+
224
+ socket.log("ready");
225
+
226
+ res.json(exercise);
227
+ })
228
+ );
229
+
230
+ app.get(
231
+ "/exercise/:slug/file/:fileName",
232
+ withHandler((req: express.Request, res: express.Response) => {
233
+ const exercise = configManager.getExercise(req.params.slug);
234
+ if (exercise && exercise.getFile) {
235
+ res.write(exercise.getFile(req.params.fileName));
236
+ res.end();
237
+ }
238
+ })
239
+ );
240
+
241
+ const textBodyParser = bodyParser.text();
242
+ app.put(
243
+ "/exercise/:slug/file/:fileName",
244
+ textBodyParser,
245
+ withHandler((req: express.Request, res: express.Response) => {
246
+ const exercise = configManager.getExercise(req.params.slug);
247
+ if (exercise && exercise.saveFile) {
248
+ exercise.saveFile(req.params.fileName, req.body);
249
+ res.end();
250
+ }
251
+ })
252
+ );
253
+
254
+ if (config?.outputPath) {
255
+ app.use("/preview", express.static(config.outputPath));
256
+ }
257
+
258
+ app.use("/", express.static(`${config?.dirPath}/_app`));
259
+ }
@@ -1,26 +1,26 @@
1
- import { IFile } from "./file";
2
- import { IConfig } from "./config";
3
- import { ISocket } from "./socket";
4
-
5
- export interface IExercise {
6
- position?: number;
7
- files: Array<IFile>;
8
- slug: string;
9
- path: string;
10
- done: boolean;
11
- language?: string | null;
12
- entry?: string | null;
13
- graded?: boolean;
14
- translations?: { [key: string]: string };
15
- title: string;
16
- getReadme: (lang: string | null) => any;
17
- getFile: (name: string) => string | Buffer;
18
- saveFile: (name: string, content: string) => void;
19
- getTestReport: () => any;
20
- test?: (sessionConfig: any, config: IConfig, socket: ISocket) => void;
21
- }
22
-
23
- export interface IExerciseData {
24
- exerciseSlug: string;
25
- files: string[];
26
- }
1
+ import { IFile } from "./file";
2
+ import { IConfig } from "./config";
3
+ import { ISocket } from "./socket";
4
+
5
+ export interface IExercise {
6
+ position?: number;
7
+ files: Array<IFile>;
8
+ slug: string;
9
+ path: string;
10
+ done: boolean;
11
+ language?: string | null;
12
+ entry?: string | null;
13
+ graded?: boolean;
14
+ translations?: { [key: string]: string };
15
+ title: string;
16
+ getReadme?: (lang: string | null) => any;
17
+ getFile?: (name: string) => string | Buffer;
18
+ saveFile?: (name: string, content: string) => void;
19
+ getTestReport?: () => any;
20
+ test?: (sessionConfig: any, config: IConfig, socket: ISocket) => void;
21
+ }
22
+
23
+ export interface IExerciseData {
24
+ exerciseSlug: string;
25
+ files: string[];
26
+ }