@learnpack/learnpack 5.0.274 → 5.0.275

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +409 -409
  2. package/lib/commands/audit.js +15 -15
  3. package/lib/commands/breakToken.js +19 -19
  4. package/lib/commands/clean.js +3 -3
  5. package/lib/commands/init.js +41 -41
  6. package/lib/commands/logout.js +3 -3
  7. package/lib/commands/serve.js +127 -70
  8. package/lib/creatorDist/assets/index-BfLyIQVh.js +10223 -10342
  9. package/lib/managers/config/index.js +77 -77
  10. package/lib/models/creator.d.ts +7 -0
  11. package/lib/utils/api.d.ts +1 -0
  12. package/lib/utils/api.js +2 -1
  13. package/lib/utils/creatorUtilities.js +14 -14
  14. package/package.json +1 -1
  15. package/src/commands/audit.ts +487 -487
  16. package/src/commands/breakToken.ts +67 -67
  17. package/src/commands/clean.ts +30 -30
  18. package/src/commands/init.ts +650 -650
  19. package/src/commands/logout.ts +38 -38
  20. package/src/commands/publish.ts +522 -522
  21. package/src/commands/serve.ts +162 -107
  22. package/src/commands/start.ts +333 -333
  23. package/src/commands/translate.ts +123 -123
  24. package/src/creator/README.md +54 -54
  25. package/src/creator/eslint.config.js +28 -28
  26. package/src/creator/src/components/syllabus/ContentIndex.tsx +312 -312
  27. package/src/creator/src/i18n.ts +28 -28
  28. package/src/creator/src/index.css +217 -217
  29. package/src/creator/src/locales/en.json +126 -126
  30. package/src/creator/src/locales/es.json +126 -126
  31. package/src/creator/src/utils/configTypes.ts +122 -122
  32. package/src/creator/src/utils/constants.ts +13 -13
  33. package/src/creator/src/utils/creatorUtils.ts +46 -46
  34. package/src/creator/src/utils/eventBus.ts +2 -2
  35. package/src/creator/src/utils/lib.ts +468 -468
  36. package/src/creator/src/utils/socket.ts +61 -61
  37. package/src/creator/src/utils/store.ts +222 -222
  38. package/src/creator/src/vite-env.d.ts +1 -1
  39. package/src/creator/vite.config.ts +13 -13
  40. package/src/creatorDist/assets/index-BfLyIQVh.js +10223 -10342
  41. package/src/managers/config/defaults.ts +49 -49
  42. package/src/managers/config/exercise.ts +364 -364
  43. package/src/managers/config/index.ts +775 -775
  44. package/src/managers/file.ts +236 -236
  45. package/src/managers/server/routes.ts +554 -554
  46. package/src/managers/session.ts +182 -182
  47. package/src/managers/telemetry.ts +188 -188
  48. package/src/models/action.ts +13 -13
  49. package/src/models/config-manager.ts +28 -28
  50. package/src/models/config.ts +106 -106
  51. package/src/models/creator.ts +47 -40
  52. package/src/models/exercise-obj.ts +30 -30
  53. package/src/models/session.ts +39 -39
  54. package/src/models/socket.ts +61 -61
  55. package/src/models/status.ts +16 -16
  56. package/src/ui/_app/app.js +141 -141
  57. package/src/ui/app.tar.gz +0 -0
  58. package/src/utils/BaseCommand.ts +56 -56
  59. package/src/utils/api.ts +31 -30
  60. package/src/utils/audit.ts +392 -392
  61. package/src/utils/checkNotInstalled.ts +267 -267
  62. package/src/utils/configBuilder.ts +82 -82
  63. package/src/utils/convertCreds.js +34 -34
  64. package/src/utils/creatorUtilities.ts +504 -504
  65. package/src/utils/incrementVersion.js +74 -74
  66. package/src/utils/misc.ts +58 -58
  67. package/src/utils/rigoActions.ts +500 -500
  68. package/src/utils/sidebarGenerator.ts +195 -195
  69. package/src/utils/templates/isolated/exercises/01-hello-world/README.es.md +26 -26
  70. package/src/utils/templates/isolated/exercises/01-hello-world/README.md +26 -26
@@ -1,775 +1,775 @@
1
- import * as path from "path"
2
- import * as fs from "fs"
3
- import * as shell from "shelljs"
4
- import { exec } from "child_process"
5
- import { promisify } from "util"
6
-
7
- import Console from "../../utils/console"
8
- import watch from "../../utils/watcher"
9
- import {
10
- ValidationError,
11
- NotFoundError,
12
- InternalError,
13
- } from "../../utils/errors"
14
- import { checkAndFixSidebar } from "../../utils/sidebarGenerator"
15
-
16
- import defaults from "./defaults"
17
- import { exercise } from "./exercise"
18
-
19
- import { rmSync } from "../file"
20
- import { IConfigObj, TMode, TAgent } from "../../models/config"
21
- import {
22
- IConfigManagerAttributes,
23
- IConfigManager,
24
- } from "../../models/config-manager"
25
- import { IFile } from "../../models/file"
26
- import { TSuggestions } from "../../models/config"
27
- import { IExercise } from "../../models/exercise-obj"
28
- /* exercise folder name standard */
29
- const execAsync = promisify(exec)
30
-
31
- // eslint-disable-next-line
32
- const fetch = require("node-fetch")
33
- // eslint-disable-next-line
34
- const chalk = require("chalk")
35
-
36
- /* exercise folder name standard */
37
-
38
- /**
39
- * Retrieves the configuration path for the learnpack package.
40
- *
41
- * @returns An object containing the configuration file path and the base directory.
42
- * @throws NotFoundError if the learn.json file is not found in the current folder.
43
- */
44
- const getConfigPath = () => {
45
- const possibleFileNames = ["learn.json", ".learn/learn.json"]
46
- const config = possibleFileNames.find(file => fs.existsSync(file)) || null
47
- if (config && fs.existsSync(".breathecode"))
48
- return { config, base: ".breathecode" }
49
- if (config === null)
50
- throw NotFoundError(
51
- "learn.json file not found on current folder, is this a learnpack package?"
52
- )
53
- return { config, base: ".learn" }
54
- }
55
-
56
- const getExercisesPath = (base: string) => {
57
- const possibleFileNames = ["./exercises", base + "/exercises", "./"]
58
- return possibleFileNames.find(file => fs.existsSync(file)) || null
59
- }
60
-
61
- const getGitpodAddress = () => {
62
- if (shell.exec("gp -h", { silent: true }).code === 0) {
63
- return shell
64
- .exec("gp url", { silent: true })
65
- .stdout.replace(/(\r\n|\n|\r)/gm, "")
66
- }
67
-
68
- Console.debug("Gitpod command line tool not found")
69
- return "http://localhost"
70
- }
71
-
72
- const getCodespacesNamespace = () => {
73
- // Example: https://orange-rotary-phone-wxpg49q5gcg4rp-3000.app.github.dev
74
-
75
- const codespace_name = shell
76
- .exec("echo $CODESPACE_NAME", { silent: true })
77
- .stdout.replace(/(\r\n|\n|\r)/gm, "")
78
-
79
- if (
80
- !codespace_name ||
81
- codespace_name === "" ||
82
- codespace_name === undefined ||
83
- codespace_name === "$CODESPACE_NAME"
84
- ) {
85
- return null
86
- }
87
-
88
- return codespace_name
89
- }
90
-
91
- const checkDuration = (configObj: IConfigObj) => {
92
- if (!configObj.exercises || !configObj.config || !configObj.config.dirPath)
93
- return
94
-
95
- const learnJSONPath = path.join(configObj.config.dirPath, "../learn.json")
96
-
97
- const learnJSON = fs.readFileSync(learnJSONPath, "utf8")
98
- const learnJSONObj = JSON.parse(learnJSON)
99
- const duration = learnJSONObj.duration
100
- if (!duration) {
101
- learnJSONObj.duration = configObj.exercises.reduce(
102
- (acc: number) => acc + 2,
103
- 0
104
- )
105
- fs.writeFileSync(learnJSONPath, JSON.stringify(learnJSONObj, null, 2))
106
- }
107
- }
108
-
109
- export default async ({
110
- grading,
111
- mode,
112
- disableGrading,
113
- version,
114
- }: IConfigManagerAttributes): Promise<IConfigManager> => {
115
- const confPath = getConfigPath()
116
-
117
- const suggestions: TSuggestions = { agent: null }
118
- Console.debug("This is the config path: ", confPath)
119
-
120
- let configObj: IConfigObj = {}
121
-
122
- if (confPath) {
123
- const learnJsonContent = fs.readFileSync(confPath.config)
124
- let hiddenBcContent = {}
125
-
126
- if (fs.existsSync(confPath.base + "/config.json")) {
127
- hiddenBcContent = fs.readFileSync(confPath.base + "/config.json")
128
- hiddenBcContent = JSON.parse(hiddenBcContent as string)
129
- if (!hiddenBcContent)
130
- throw new Error(
131
- `Invalid ${confPath.base}/config.json syntax: Unable to parse.`
132
- )
133
- }
134
-
135
- const jsonConfig = JSON.parse(`${learnJsonContent}`)
136
-
137
- if (jsonConfig?.editor?.agent) {
138
- suggestions.agent = jsonConfig.editor.agent
139
- }
140
-
141
- if (!jsonConfig)
142
- throw new Error(`Invalid ${confPath.config} syntax: Unable to parse.`)
143
-
144
- let session: number
145
-
146
- // add using id to the installation
147
- if (!jsonConfig.session) {
148
- session = Math.floor(Math.random() * 10_000_000_000_000_000_000)
149
- } else {
150
- session = jsonConfig.session
151
- delete jsonConfig.session
152
- }
153
-
154
- configObj = deepMerge(hiddenBcContent, {
155
- config: jsonConfig,
156
- session: session,
157
- })
158
- } else {
159
- throw ValidationError(
160
- "No learn.json file has been found, make sure you are in the correct directory. To start a new LearnPack package run: $ learnpack init my-course-name"
161
- )
162
- }
163
-
164
- configObj = deepMerge(defaults || {}, configObj, {
165
- config: {
166
- grading: grading || configObj.config?.grading,
167
- configPath: confPath.config,
168
- },
169
- })
170
- if (!configObj.config)
171
- throw InternalError("Config object not found")
172
-
173
- configObj.config.outputPath = confPath.base + "/dist"
174
-
175
- Console.debug("This is your configuration object: ", {
176
- ...configObj,
177
- exercises: configObj.exercises ?
178
- configObj.exercises.map(e => e.slug) :
179
- [],
180
- })
181
-
182
- // auto detect agent (if possible)
183
- const codespaces_workspace = getCodespacesNamespace()
184
- Console.debug("This is the codespace namespace: ", codespaces_workspace)
185
-
186
- if (!configObj.config.editor) {
187
- configObj.config.editor = {}
188
- }
189
-
190
- configObj.config.suggestions = suggestions
191
-
192
- if (shell.which("gp") && configObj && configObj.config) {
193
- Console.debug("Gitpod detected")
194
- configObj.address = getGitpodAddress()
195
- configObj.config.publicUrl = `https://${
196
- configObj.config.port
197
- }-${configObj.address?.slice(8)}`
198
- configObj.config.editor.agent = "vscode"
199
- } else if (configObj.config && Boolean(codespaces_workspace)) {
200
- Console.debug("Codespaces detected: ", codespaces_workspace)
201
- configObj.address = `https://${codespaces_workspace}.github.dev`
202
- configObj.config.publicUrl = `https://${codespaces_workspace}-${configObj.config.port}.app.github.dev`
203
- configObj.config.editor.agent = "vscode"
204
- } else {
205
- Console.debug("Neither Gitpod nor Codespaces detected, using localhost.")
206
- configObj.address = `http://localhost:${configObj.config.port}`
207
- configObj.config.publicUrl = `http://localhost:${configObj.config.port}`
208
- configObj.config.editor.agent =
209
- process.env.TERM_PROGRAM === "vscode" ? "vscode" : "os"
210
- }
211
-
212
- if (configObj.config.editor.agent === "vscode" && isCodeCommandAvailable()) {
213
- const extensionName = "learn-pack.learnpack-vscode"
214
-
215
- if (!isExtensionInstalled(extensionName)) {
216
- Console.info(
217
- "The LearnPack extension is not installed, trying to install it automatically."
218
- )
219
-
220
- if (!installExtension(extensionName)) {
221
- configObj.config.warnings = {
222
- extension: EXTENSION_INSTALLATION_STEPS,
223
- }
224
- Console.warning(
225
- "The LearnPack extension is not installed and this tutorial is meant to be run inside VSCode. Please install the LearnPack extension."
226
- )
227
- }
228
- }
229
- }
230
-
231
- if (
232
- configObj.config.suggestions &&
233
- configObj.config.editor &&
234
- configObj.config.suggestions.agent !== null &&
235
- configObj.config.suggestions.agent !== configObj.config.editor.agent
236
- ) {
237
- Console.warning(
238
- `The suggested agent "${configObj.config.suggestions.agent}" is different from the detected agent "${configObj.config.editor.agent}"`
239
- )
240
-
241
- try {
242
- configObj.config.warnings = {
243
- ...configObj.config.warnings,
244
- agent: buildAgentWarning(
245
- configObj.config.editor.agent,
246
- configObj.config.suggestions.agent
247
- ),
248
- }
249
- } catch {
250
- Console.error("IMPOSSIBLE TO SET WARNING")
251
- }
252
- } else {
253
- configObj.config.warnings.agent = undefined
254
- }
255
-
256
- if (configObj.config && !configObj.config.publicUrl)
257
- configObj.config.publicUrl = `${configObj.address}:${configObj.config.port}`
258
-
259
- if (configObj.config && !configObj.config.editor.mode && mode) {
260
- configObj.config.editor.mode = mode as TMode
261
- }
262
-
263
- configObj.config.editor.mode =
264
- process.env.TERM_PROGRAM === "vscode" ? "extension" : "preview"
265
-
266
- if (version)
267
- configObj.config.editor.version = version
268
- else if (configObj.config.editor.version === null) {
269
- Console.debug("Config version not found, downloading default.")
270
- const resp = await fetch(
271
- "https://raw.githubusercontent.com/learnpack/ide/master/package.json"
272
- )
273
- const packageJSON = await resp.json()
274
- configObj.config.editor.version = packageJSON.version || "5.0.0"
275
- }
276
-
277
- configObj.config.dirPath = "./" + confPath.base
278
- configObj.config.exercisesPath = getExercisesPath(confPath.base) || "./"
279
-
280
- if (configObj.config.variables) {
281
- const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"])
282
-
283
- const variableKeys = Object.keys(configObj.config.variables)
284
- const promises = []
285
-
286
- for (const v of variableKeys) {
287
- if (Object.prototype.hasOwnProperty.call(configObj.config.variables, v)) {
288
- const variable = configObj.config.variables[v]
289
-
290
- if (typeof variable === "string") {
291
- continue
292
- }
293
-
294
- const type = variable.type
295
-
296
- if (type === "command") {
297
- const promise = (async () => {
298
- try {
299
- // Validate the command
300
- if (!allowedCommands.has(variable.source.split(" ")[0])) {
301
- throw new Error("Command not allowed")
302
- }
303
-
304
- // Execute the code and replace the value
305
- const { stdout } = await execAsync(variable.source)
306
- if (!configObj.config || !configObj.config.variables)
307
- return
308
-
309
- configObj.config.variables[v] = stdout.trim()
310
- } catch (error) {
311
- console.error(`Error executing code: ${error}`)
312
- }
313
- })()
314
- promises.push(promise)
315
- } else if (type === "string") {
316
- configObj.config.variables[v] = variable.source
317
- }
318
- }
319
- }
320
-
321
- await Promise.all(promises)
322
- }
323
-
324
- return {
325
- validLanguages: {},
326
- get: () => {
327
- return configObj
328
- },
329
- validateEngine: function (language: string, server: any, socket: any) {
330
- // eslint-disable-next-line
331
- const alias = (_l: string) => {
332
- const map: any = {
333
- python3: "python",
334
- }
335
- if (map[_l])
336
- return map[_l]
337
- return _l
338
- }
339
-
340
- // decode aliases
341
- language = alias(language)
342
-
343
- if (this.validLanguages[language])
344
- return true
345
-
346
- Console.debug(`Validating engine for ${language} compilation`)
347
- let result = shell.exec("learnpack plugins", { silent: true })
348
-
349
- if (
350
- result.code === 0 &&
351
- result.stdout.includes(`@learnpack/${language}`)
352
- ) {
353
- this.validLanguages[language] = true
354
- return true
355
- }
356
-
357
- Console.info(`Language engine for ${language} not found, installing...`)
358
- // Install the compiler in their new versions
359
- result = shell.exec(`learnpack plugins:install @learnpack/${language}`, {
360
- silent: true,
361
- })
362
- if (result.code === 0) {
363
- socket.log(
364
- "compiling",
365
- "Installing the python compiler, you will have to reset the exercises after installation by writing on your terminal: $ learnpack run"
366
- )
367
- Console.info(
368
- `Successfully installed the ${language} exercise engine, \n please start learnpack again by running the following command: \n ${chalk.white(
369
- "$ learnpack start"
370
- )}\n\n `
371
- )
372
- server.terminate()
373
- return false
374
- }
375
-
376
- this.validLanguages[language] = false
377
- socket.error(`Error installing ${language} exercise engine`)
378
- Console.error(`Error installing ${language} exercise engine`)
379
- Console.log(result.stdout)
380
- throw InternalError(`Error installing ${language} exercise engine`)
381
- },
382
- logout: () => {
383
- if (configObj.config) {
384
- rmSync(configObj.config.dirPath + "/.session")
385
- }
386
- },
387
- clean: async () => {
388
- if (configObj.config) {
389
- if (configObj.config.outputPath) {
390
- rmSync(configObj.config.outputPath)
391
- }
392
-
393
- rmSync(configObj.config.dirPath + "/_app")
394
- rmSync(configObj.config.dirPath + "/reports")
395
- rmSync(configObj.config.dirPath + "/.session")
396
- rmSync(configObj.config.dirPath + "/resets")
397
-
398
- // clean __pycache__ folder
399
- rmSync(configObj.config.dirPath + "/../__pycache__")
400
-
401
- // clean the __pycache__ for each exercise it exists
402
- if (configObj.exercises) {
403
- for (const e of configObj.exercises) {
404
- if (fs.existsSync(e.path + "/__pycache__")) {
405
- rmSync(e.path + "/__pycache__")
406
- }
407
- }
408
- }
409
-
410
- // clean tag gz
411
- if (fs.existsSync(configObj.config.dirPath + "/app.tar.gz"))
412
- fs.unlinkSync(configObj.config.dirPath + "/app.tar.gz")
413
-
414
- if (fs.existsSync(configObj.config.dirPath + "/config.json"))
415
- fs.unlinkSync(configObj.config.dirPath + "/config.json")
416
-
417
- if (fs.existsSync(configObj.config.dirPath + "/telemetry.json"))
418
- fs.unlinkSync(configObj.config.dirPath + "/telemetry.json")
419
-
420
- if (fs.existsSync(configObj.config.dirPath + "/vscode_queue.json"))
421
- fs.unlinkSync(configObj.config.dirPath + "/vscode_queue.json")
422
-
423
- await checkAndFixSidebar(configObj, true)
424
-
425
- checkDuration(configObj)
426
- }
427
- },
428
- getExercise: slug => {
429
- Console.debug("ExercisePath Slug", slug)
430
- const exercise = (configObj.exercises || []).find(
431
- ex => ex.slug === slug
432
- )
433
- if (!exercise)
434
- throw ValidationError(`Exercise ${slug} not found`)
435
-
436
- return exercise
437
- },
438
- getAllExercises: () => {
439
- return configObj.exercises
440
- },
441
- startExercise: function (slug: string) {
442
- const exercise = this.getExercise(slug)
443
-
444
- // set config.json with current exercise
445
- configObj.currentExercise = exercise.slug
446
-
447
- this.save()
448
-
449
- // eslint-disable-next-line
450
- exercise.files.forEach((f: IFile) => {
451
- if (configObj.config) {
452
- const _path = configObj.config.outputPath + "/" + f.name
453
- if (f.hidden === false && fs.existsSync(_path))
454
- fs.unlinkSync(_path)
455
- }
456
- })
457
-
458
- return exercise
459
- },
460
- noCurrentExercise: function () {
461
- configObj.currentExercise = null
462
- this.save()
463
- },
464
- reset: slug => {
465
- if (
466
- configObj.config &&
467
- !fs.existsSync(`${configObj.config.dirPath}/resets/` + slug)
468
- )
469
- throw ValidationError("Could not find the original files for " + slug)
470
-
471
- const exercise = (configObj.exercises || []).find(
472
- ex => ex.slug === slug
473
- )
474
- if (!exercise)
475
- throw ValidationError(`Exercise ${slug} not found on the configuration`)
476
-
477
- if (configObj.config) {
478
- for (const fileName of fs.readdirSync(
479
- `${configObj.config.dirPath}/resets/${slug}/`
480
- )) {
481
- const content = fs.readFileSync(
482
- `${configObj.config?.dirPath}/resets/${slug}/${fileName}`
483
- )
484
- fs.writeFileSync(`${exercise.path}/${fileName}`, content)
485
- }
486
- }
487
- },
488
-
489
- buildIndex: function () {
490
- Console.info("Building the exercise index...")
491
-
492
- const isDirectory = (source: string) => {
493
- const name = path.basename(source)
494
- if (name === path.basename(configObj?.config?.dirPath || ""))
495
- return false
496
- // ignore folders that start with a dot
497
- if (name.charAt(0) === "." || name.charAt(0) === "_")
498
- return false
499
-
500
- return fs.lstatSync(source).isDirectory()
501
- }
502
-
503
- const getDirectories = (source: string) =>
504
- fs
505
- .readdirSync(source)
506
- .map(name => path.join(source, name))
507
- .filter(isDirectory)
508
- // add the .learn folder
509
- if (!fs.existsSync(confPath.base))
510
- fs.mkdirSync(confPath.base)
511
- // add the outout folder where webpack will publish the the html/css/js files
512
- if (
513
- configObj.config &&
514
- configObj.config.outputPath &&
515
- !fs.existsSync(configObj.config.outputPath)
516
- )
517
- fs.mkdirSync(configObj.config.outputPath)
518
-
519
- // TODO: we could use npm library front-mater to read the title of the exercises from the README.md
520
- const grupedByDirectory = getDirectories(
521
- configObj?.config?.exercisesPath || ""
522
- )
523
- configObj.exercises =
524
- grupedByDirectory.length > 0 ?
525
- grupedByDirectory.map((path, position) =>
526
- exercise(path, position, configObj)
527
- ) :
528
- [exercise(configObj?.config?.exercisesPath || "", 0, configObj)]
529
-
530
- if (configObj.config) {
531
- configObj.config.editor.agent =
532
- process.env.TERM_PROGRAM === "vscode" ? "vscode" : "os"
533
- }
534
-
535
- this.save()
536
- },
537
- createExercise: (slug: string, content: string, language: string) => {
538
- try {
539
- const dirPath = `${configObj.config?.exercisesPath}/${slug}`
540
- if (!fs.existsSync(dirPath))
541
- fs.mkdirSync(dirPath, { recursive: true })
542
- const isEnglish = language === "us" || language === "en"
543
- const fileName = isEnglish ? "README.md" : `README.${language}.md`
544
- fs.writeFileSync(`${dirPath}/${fileName}`, content)
545
-
546
- return true
547
- } catch (error) {
548
- Console.error("Error creating exercise: ", error)
549
- return false
550
- }
551
- },
552
-
553
- deleteExercise: (slug: string) => {
554
- const dirPath = `${configObj.config?.exercisesPath}/${slug}`
555
- if (fs.existsSync(dirPath)) {
556
- fs.rmSync(dirPath, { recursive: true, force: true })
557
- return true
558
- }
559
-
560
- return false
561
- },
562
-
563
- getSidebar: () => {
564
- const sidebarPath = path.join(
565
- configObj.config?.dirPath || "",
566
- "sidebar.json"
567
- )
568
- if (fs.existsSync(sidebarPath)) {
569
- return JSON.parse(fs.readFileSync(sidebarPath, "utf8"))
570
- }
571
-
572
- return {}
573
- },
574
- watchIndex: function (onChange: (filename: string) => void) {
575
- if (configObj.config && !configObj.config.exercisesPath)
576
- throw ValidationError(
577
- "No exercises directory to watch: " + configObj.config.exercisesPath
578
- )
579
-
580
- this.buildIndex()
581
-
582
- watch(configObj?.config?.exercisesPath || "", onChange)
583
- .then(() => {
584
- Console.debug("Changes detected on your exercises")
585
- this.buildIndex()
586
- // if (onChange) onChange(filename);
587
- })
588
- .catch(error => {
589
- throw error
590
- })
591
- },
592
-
593
- save: () => {
594
- Console.debug("Saving configuration with: ", configObj)
595
- // remove the duplicates form the actions array
596
- // configObj.config.actions = [...new Set(configObj.config.actions)];
597
- if (configObj.config) {
598
- configObj.config.translations = [
599
- ...new Set(configObj.config.translations),
600
- ]
601
- fs.writeFileSync(
602
- configObj.config.dirPath + "/config.json",
603
- JSON.stringify(configObj, null, 4)
604
- )
605
- }
606
- },
607
- } as IConfigManager
608
- }
609
-
610
- function deepMerge(...sources: any): any {
611
- let acc: any = {}
612
- for (const source of sources) {
613
- if (Array.isArray(source)) {
614
- if (!Array.isArray(acc)) {
615
- acc = []
616
- }
617
-
618
- acc = [...source]
619
- } else if (source instanceof Object) {
620
- // eslint-disable-next-line
621
- for (let [key, value] of Object.entries(source)) {
622
- if (value instanceof Object && key in acc) {
623
- value = deepMerge(acc[key], value)
624
- }
625
-
626
- if (value !== undefined)
627
- acc = { ...acc, [key]: value }
628
- }
629
- }
630
- }
631
-
632
- return acc
633
- }
634
-
635
- const buildAgentWarning = (current: TAgent, suggested: TAgent): string => {
636
- const message = `# Agent mismatch!\n
637
-
638
- In LearnPack, the agent is in charge of running the LearnPack interface.
639
-
640
- You're currently using LearnPack through \`${current}\` but the suggested agent is \`${suggested}\`.
641
-
642
- We recommend strongly recommend changing your agent.
643
-
644
- ${stepsToChangeAgent(suggested)}
645
- `
646
-
647
- return message
648
- }
649
-
650
- const stepsToChangeAgent = (agent: TAgent): string => {
651
- if (agent === "vscode") {
652
- return `
653
- # Steps to Change Agent to VSCode
654
-
655
- 1. **Install VSCode**:
656
- - Visit the [VSCode website](https://code.visualstudio.com/Download) and download the latest version.
657
- - Follow the installation instructions for your operating system.
658
-
659
- 2. **Install LearnPack VSCode Extension**:
660
- - Open VSCode.
661
- - Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing \`Ctrl+Shift+X\`.
662
- - Search for "LearnPack" and click "Install".
663
- - If the extension is already installed but disabled, enable it.
664
-
665
- 3. **Run LearnPack in VSCode**:
666
- - Open your terminal in VSCode.
667
- - Navigate to your LearnPack project directory.
668
- - Run the following command:
669
- \`\`\`sh
670
- learnpack start
671
- \`\`\`
672
-
673
- We strongly recommend using VSCode for a better learning experience.
674
- `
675
- }
676
-
677
- if (agent === "os") {
678
- return `
679
- # Steps to Change Agent to OS
680
-
681
- This learning package was designed to run outside of VSCode. We strongly recommend closing VSCode and running the package independently.
682
-
683
- 1. **Close VSCode**:
684
- - Save your work and close the VSCode application.
685
-
686
- 2. **Open a New Terminal**:
687
- - Open a terminal or command prompt on your operating system.
688
-
689
- 3. **Navigate to Your LearnPack Project Directory**:
690
- - Use the \`cd\` command to navigate to the directory where your LearnPack project is located.
691
-
692
- 4. **Run LearnPack**:
693
- - Run the following command to start LearnPack:
694
- \`\`\`sh
695
- learnpack start
696
- \`\`\`
697
-
698
- We strongly recommend running the package independently for a better learning experience.
699
- `
700
- }
701
-
702
- return ""
703
- }
704
-
705
- /**
706
- * Checks if the 'code' command is available in the terminal.
707
- *
708
- * @returns {boolean} True if the 'code' command is available, false otherwise.
709
- */
710
- const isCodeCommandAvailable = (): boolean => {
711
- return shell.which("code") !== null
712
- }
713
-
714
- /**
715
- * Checks if a specific VSCode extension is installed.
716
- *
717
- * @param {string} extensionName - The name of the extension to check.
718
- * @returns {boolean} True if the extension is installed, false otherwise.
719
- */
720
- const isExtensionInstalled = (extensionName: string): boolean => {
721
- if (!isCodeCommandAvailable()) {
722
- throw new Error(
723
- "The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
724
- )
725
- }
726
-
727
- const result = shell.exec("code --list-extensions", { silent: true })
728
- return result.stdout.split("\n").includes(extensionName)
729
- }
730
-
731
- const EXTENSION_INSTALLATION_STEPS = `
732
- # Steps to Install LearnPack VSCode Extension
733
-
734
- 1. **Open VSCode**:
735
- - Launch the Visual Studio Code application on your computer.
736
-
737
- 2. **Go to Extensions View**:
738
- - Click on the Extensions icon in the Activity Bar on the side of the window.
739
- - Alternatively, you can open the Extensions view by pressing \`Ctrl+Shift+X\`.
740
-
741
- 3. **Search for LearnPack**:
742
- - In the Extensions view, type "LearnPack" into the search bar.
743
-
744
- 4. **Install the Extension**:
745
- - Find the "LearnPack" extension in the search results and click the "Install" button.
746
- - If the extension is already installed but disabled, click the "Enable" button.
747
-
748
- 5. **Verify Installation**:
749
- - Once installed, you can verify the installation by running the following command in the terminal:
750
- \`\`\`sh
751
- code --list-extensions | grep learn-pack.learnpack-vscode
752
- \`\`\`
753
- - If the extension is listed, it means the installation was successful.
754
-
755
- We strongly recommend using the LearnPack extension in VSCode for a better learning experience.
756
- `
757
-
758
- /**
759
- * Installs the LearnPack VSCode extension if the 'code' command is available.
760
- *
761
- * @param {string} extensionName - The name of the extension to install.
762
- * @returns {boolean} True if the installation was successful, false otherwise.
763
- */
764
- const installExtension = (extensionName: string): boolean => {
765
- if (!isCodeCommandAvailable()) {
766
- throw new Error(
767
- "The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
768
- )
769
- }
770
-
771
- const result = shell.exec(`code --install-extension ${extensionName}`, {
772
- silent: true,
773
- })
774
- return result.code === 0
775
- }
1
+ import * as path from "path"
2
+ import * as fs from "fs"
3
+ import * as shell from "shelljs"
4
+ import { exec } from "child_process"
5
+ import { promisify } from "util"
6
+
7
+ import Console from "../../utils/console"
8
+ import watch from "../../utils/watcher"
9
+ import {
10
+ ValidationError,
11
+ NotFoundError,
12
+ InternalError,
13
+ } from "../../utils/errors"
14
+ import { checkAndFixSidebar } from "../../utils/sidebarGenerator"
15
+
16
+ import defaults from "./defaults"
17
+ import { exercise } from "./exercise"
18
+
19
+ import { rmSync } from "../file"
20
+ import { IConfigObj, TMode, TAgent } from "../../models/config"
21
+ import {
22
+ IConfigManagerAttributes,
23
+ IConfigManager,
24
+ } from "../../models/config-manager"
25
+ import { IFile } from "../../models/file"
26
+ import { TSuggestions } from "../../models/config"
27
+ import { IExercise } from "../../models/exercise-obj"
28
+ /* exercise folder name standard */
29
+ const execAsync = promisify(exec)
30
+
31
+ // eslint-disable-next-line
32
+ const fetch = require("node-fetch")
33
+ // eslint-disable-next-line
34
+ const chalk = require("chalk")
35
+
36
+ /* exercise folder name standard */
37
+
38
+ /**
39
+ * Retrieves the configuration path for the learnpack package.
40
+ *
41
+ * @returns An object containing the configuration file path and the base directory.
42
+ * @throws NotFoundError if the learn.json file is not found in the current folder.
43
+ */
44
+ const getConfigPath = () => {
45
+ const possibleFileNames = ["learn.json", ".learn/learn.json"]
46
+ const config = possibleFileNames.find(file => fs.existsSync(file)) || null
47
+ if (config && fs.existsSync(".breathecode"))
48
+ return { config, base: ".breathecode" }
49
+ if (config === null)
50
+ throw NotFoundError(
51
+ "learn.json file not found on current folder, is this a learnpack package?"
52
+ )
53
+ return { config, base: ".learn" }
54
+ }
55
+
56
+ const getExercisesPath = (base: string) => {
57
+ const possibleFileNames = ["./exercises", base + "/exercises", "./"]
58
+ return possibleFileNames.find(file => fs.existsSync(file)) || null
59
+ }
60
+
61
+ const getGitpodAddress = () => {
62
+ if (shell.exec("gp -h", { silent: true }).code === 0) {
63
+ return shell
64
+ .exec("gp url", { silent: true })
65
+ .stdout.replace(/(\r\n|\n|\r)/gm, "")
66
+ }
67
+
68
+ Console.debug("Gitpod command line tool not found")
69
+ return "http://localhost"
70
+ }
71
+
72
+ const getCodespacesNamespace = () => {
73
+ // Example: https://orange-rotary-phone-wxpg49q5gcg4rp-3000.app.github.dev
74
+
75
+ const codespace_name = shell
76
+ .exec("echo $CODESPACE_NAME", { silent: true })
77
+ .stdout.replace(/(\r\n|\n|\r)/gm, "")
78
+
79
+ if (
80
+ !codespace_name ||
81
+ codespace_name === "" ||
82
+ codespace_name === undefined ||
83
+ codespace_name === "$CODESPACE_NAME"
84
+ ) {
85
+ return null
86
+ }
87
+
88
+ return codespace_name
89
+ }
90
+
91
+ const checkDuration = (configObj: IConfigObj) => {
92
+ if (!configObj.exercises || !configObj.config || !configObj.config.dirPath)
93
+ return
94
+
95
+ const learnJSONPath = path.join(configObj.config.dirPath, "../learn.json")
96
+
97
+ const learnJSON = fs.readFileSync(learnJSONPath, "utf8")
98
+ const learnJSONObj = JSON.parse(learnJSON)
99
+ const duration = learnJSONObj.duration
100
+ if (!duration) {
101
+ learnJSONObj.duration = configObj.exercises.reduce(
102
+ (acc: number) => acc + 2,
103
+ 0
104
+ )
105
+ fs.writeFileSync(learnJSONPath, JSON.stringify(learnJSONObj, null, 2))
106
+ }
107
+ }
108
+
109
+ export default async ({
110
+ grading,
111
+ mode,
112
+ disableGrading,
113
+ version,
114
+ }: IConfigManagerAttributes): Promise<IConfigManager> => {
115
+ const confPath = getConfigPath()
116
+
117
+ const suggestions: TSuggestions = { agent: null }
118
+ Console.debug("This is the config path: ", confPath)
119
+
120
+ let configObj: IConfigObj = {}
121
+
122
+ if (confPath) {
123
+ const learnJsonContent = fs.readFileSync(confPath.config)
124
+ let hiddenBcContent = {}
125
+
126
+ if (fs.existsSync(confPath.base + "/config.json")) {
127
+ hiddenBcContent = fs.readFileSync(confPath.base + "/config.json")
128
+ hiddenBcContent = JSON.parse(hiddenBcContent as string)
129
+ if (!hiddenBcContent)
130
+ throw new Error(
131
+ `Invalid ${confPath.base}/config.json syntax: Unable to parse.`
132
+ )
133
+ }
134
+
135
+ const jsonConfig = JSON.parse(`${learnJsonContent}`)
136
+
137
+ if (jsonConfig?.editor?.agent) {
138
+ suggestions.agent = jsonConfig.editor.agent
139
+ }
140
+
141
+ if (!jsonConfig)
142
+ throw new Error(`Invalid ${confPath.config} syntax: Unable to parse.`)
143
+
144
+ let session: number
145
+
146
+ // add using id to the installation
147
+ if (!jsonConfig.session) {
148
+ session = Math.floor(Math.random() * 10_000_000_000_000_000_000)
149
+ } else {
150
+ session = jsonConfig.session
151
+ delete jsonConfig.session
152
+ }
153
+
154
+ configObj = deepMerge(hiddenBcContent, {
155
+ config: jsonConfig,
156
+ session: session,
157
+ })
158
+ } else {
159
+ throw ValidationError(
160
+ "No learn.json file has been found, make sure you are in the correct directory. To start a new LearnPack package run: $ learnpack init my-course-name"
161
+ )
162
+ }
163
+
164
+ configObj = deepMerge(defaults || {}, configObj, {
165
+ config: {
166
+ grading: grading || configObj.config?.grading,
167
+ configPath: confPath.config,
168
+ },
169
+ })
170
+ if (!configObj.config)
171
+ throw InternalError("Config object not found")
172
+
173
+ configObj.config.outputPath = confPath.base + "/dist"
174
+
175
+ Console.debug("This is your configuration object: ", {
176
+ ...configObj,
177
+ exercises: configObj.exercises ?
178
+ configObj.exercises.map(e => e.slug) :
179
+ [],
180
+ })
181
+
182
+ // auto detect agent (if possible)
183
+ const codespaces_workspace = getCodespacesNamespace()
184
+ Console.debug("This is the codespace namespace: ", codespaces_workspace)
185
+
186
+ if (!configObj.config.editor) {
187
+ configObj.config.editor = {}
188
+ }
189
+
190
+ configObj.config.suggestions = suggestions
191
+
192
+ if (shell.which("gp") && configObj && configObj.config) {
193
+ Console.debug("Gitpod detected")
194
+ configObj.address = getGitpodAddress()
195
+ configObj.config.publicUrl = `https://${
196
+ configObj.config.port
197
+ }-${configObj.address?.slice(8)}`
198
+ configObj.config.editor.agent = "vscode"
199
+ } else if (configObj.config && Boolean(codespaces_workspace)) {
200
+ Console.debug("Codespaces detected: ", codespaces_workspace)
201
+ configObj.address = `https://${codespaces_workspace}.github.dev`
202
+ configObj.config.publicUrl = `https://${codespaces_workspace}-${configObj.config.port}.app.github.dev`
203
+ configObj.config.editor.agent = "vscode"
204
+ } else {
205
+ Console.debug("Neither Gitpod nor Codespaces detected, using localhost.")
206
+ configObj.address = `http://localhost:${configObj.config.port}`
207
+ configObj.config.publicUrl = `http://localhost:${configObj.config.port}`
208
+ configObj.config.editor.agent =
209
+ process.env.TERM_PROGRAM === "vscode" ? "vscode" : "os"
210
+ }
211
+
212
+ if (configObj.config.editor.agent === "vscode" && isCodeCommandAvailable()) {
213
+ const extensionName = "learn-pack.learnpack-vscode"
214
+
215
+ if (!isExtensionInstalled(extensionName)) {
216
+ Console.info(
217
+ "The LearnPack extension is not installed, trying to install it automatically."
218
+ )
219
+
220
+ if (!installExtension(extensionName)) {
221
+ configObj.config.warnings = {
222
+ extension: EXTENSION_INSTALLATION_STEPS,
223
+ }
224
+ Console.warning(
225
+ "The LearnPack extension is not installed and this tutorial is meant to be run inside VSCode. Please install the LearnPack extension."
226
+ )
227
+ }
228
+ }
229
+ }
230
+
231
+ if (
232
+ configObj.config.suggestions &&
233
+ configObj.config.editor &&
234
+ configObj.config.suggestions.agent !== null &&
235
+ configObj.config.suggestions.agent !== configObj.config.editor.agent
236
+ ) {
237
+ Console.warning(
238
+ `The suggested agent "${configObj.config.suggestions.agent}" is different from the detected agent "${configObj.config.editor.agent}"`
239
+ )
240
+
241
+ try {
242
+ configObj.config.warnings = {
243
+ ...configObj.config.warnings,
244
+ agent: buildAgentWarning(
245
+ configObj.config.editor.agent,
246
+ configObj.config.suggestions.agent
247
+ ),
248
+ }
249
+ } catch {
250
+ Console.error("IMPOSSIBLE TO SET WARNING")
251
+ }
252
+ } else {
253
+ configObj.config.warnings.agent = undefined
254
+ }
255
+
256
+ if (configObj.config && !configObj.config.publicUrl)
257
+ configObj.config.publicUrl = `${configObj.address}:${configObj.config.port}`
258
+
259
+ if (configObj.config && !configObj.config.editor.mode && mode) {
260
+ configObj.config.editor.mode = mode as TMode
261
+ }
262
+
263
+ configObj.config.editor.mode =
264
+ process.env.TERM_PROGRAM === "vscode" ? "extension" : "preview"
265
+
266
+ if (version)
267
+ configObj.config.editor.version = version
268
+ else if (configObj.config.editor.version === null) {
269
+ Console.debug("Config version not found, downloading default.")
270
+ const resp = await fetch(
271
+ "https://raw.githubusercontent.com/learnpack/ide/master/package.json"
272
+ )
273
+ const packageJSON = await resp.json()
274
+ configObj.config.editor.version = packageJSON.version || "5.0.0"
275
+ }
276
+
277
+ configObj.config.dirPath = "./" + confPath.base
278
+ configObj.config.exercisesPath = getExercisesPath(confPath.base) || "./"
279
+
280
+ if (configObj.config.variables) {
281
+ const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"])
282
+
283
+ const variableKeys = Object.keys(configObj.config.variables)
284
+ const promises = []
285
+
286
+ for (const v of variableKeys) {
287
+ if (Object.prototype.hasOwnProperty.call(configObj.config.variables, v)) {
288
+ const variable = configObj.config.variables[v]
289
+
290
+ if (typeof variable === "string") {
291
+ continue
292
+ }
293
+
294
+ const type = variable.type
295
+
296
+ if (type === "command") {
297
+ const promise = (async () => {
298
+ try {
299
+ // Validate the command
300
+ if (!allowedCommands.has(variable.source.split(" ")[0])) {
301
+ throw new Error("Command not allowed")
302
+ }
303
+
304
+ // Execute the code and replace the value
305
+ const { stdout } = await execAsync(variable.source)
306
+ if (!configObj.config || !configObj.config.variables)
307
+ return
308
+
309
+ configObj.config.variables[v] = stdout.trim()
310
+ } catch (error) {
311
+ console.error(`Error executing code: ${error}`)
312
+ }
313
+ })()
314
+ promises.push(promise)
315
+ } else if (type === "string") {
316
+ configObj.config.variables[v] = variable.source
317
+ }
318
+ }
319
+ }
320
+
321
+ await Promise.all(promises)
322
+ }
323
+
324
+ return {
325
+ validLanguages: {},
326
+ get: () => {
327
+ return configObj
328
+ },
329
+ validateEngine: function (language: string, server: any, socket: any) {
330
+ // eslint-disable-next-line
331
+ const alias = (_l: string) => {
332
+ const map: any = {
333
+ python3: "python",
334
+ }
335
+ if (map[_l])
336
+ return map[_l]
337
+ return _l
338
+ }
339
+
340
+ // decode aliases
341
+ language = alias(language)
342
+
343
+ if (this.validLanguages[language])
344
+ return true
345
+
346
+ Console.debug(`Validating engine for ${language} compilation`)
347
+ let result = shell.exec("learnpack plugins", { silent: true })
348
+
349
+ if (
350
+ result.code === 0 &&
351
+ result.stdout.includes(`@learnpack/${language}`)
352
+ ) {
353
+ this.validLanguages[language] = true
354
+ return true
355
+ }
356
+
357
+ Console.info(`Language engine for ${language} not found, installing...`)
358
+ // Install the compiler in their new versions
359
+ result = shell.exec(`learnpack plugins:install @learnpack/${language}`, {
360
+ silent: true,
361
+ })
362
+ if (result.code === 0) {
363
+ socket.log(
364
+ "compiling",
365
+ "Installing the python compiler, you will have to reset the exercises after installation by writing on your terminal: $ learnpack run"
366
+ )
367
+ Console.info(
368
+ `Successfully installed the ${language} exercise engine, \n please start learnpack again by running the following command: \n ${chalk.white(
369
+ "$ learnpack start"
370
+ )}\n\n `
371
+ )
372
+ server.terminate()
373
+ return false
374
+ }
375
+
376
+ this.validLanguages[language] = false
377
+ socket.error(`Error installing ${language} exercise engine`)
378
+ Console.error(`Error installing ${language} exercise engine`)
379
+ Console.log(result.stdout)
380
+ throw InternalError(`Error installing ${language} exercise engine`)
381
+ },
382
+ logout: () => {
383
+ if (configObj.config) {
384
+ rmSync(configObj.config.dirPath + "/.session")
385
+ }
386
+ },
387
+ clean: async () => {
388
+ if (configObj.config) {
389
+ if (configObj.config.outputPath) {
390
+ rmSync(configObj.config.outputPath)
391
+ }
392
+
393
+ rmSync(configObj.config.dirPath + "/_app")
394
+ rmSync(configObj.config.dirPath + "/reports")
395
+ rmSync(configObj.config.dirPath + "/.session")
396
+ rmSync(configObj.config.dirPath + "/resets")
397
+
398
+ // clean __pycache__ folder
399
+ rmSync(configObj.config.dirPath + "/../__pycache__")
400
+
401
+ // clean the __pycache__ for each exercise it exists
402
+ if (configObj.exercises) {
403
+ for (const e of configObj.exercises) {
404
+ if (fs.existsSync(e.path + "/__pycache__")) {
405
+ rmSync(e.path + "/__pycache__")
406
+ }
407
+ }
408
+ }
409
+
410
+ // clean tag gz
411
+ if (fs.existsSync(configObj.config.dirPath + "/app.tar.gz"))
412
+ fs.unlinkSync(configObj.config.dirPath + "/app.tar.gz")
413
+
414
+ if (fs.existsSync(configObj.config.dirPath + "/config.json"))
415
+ fs.unlinkSync(configObj.config.dirPath + "/config.json")
416
+
417
+ if (fs.existsSync(configObj.config.dirPath + "/telemetry.json"))
418
+ fs.unlinkSync(configObj.config.dirPath + "/telemetry.json")
419
+
420
+ if (fs.existsSync(configObj.config.dirPath + "/vscode_queue.json"))
421
+ fs.unlinkSync(configObj.config.dirPath + "/vscode_queue.json")
422
+
423
+ await checkAndFixSidebar(configObj, true)
424
+
425
+ checkDuration(configObj)
426
+ }
427
+ },
428
+ getExercise: slug => {
429
+ Console.debug("ExercisePath Slug", slug)
430
+ const exercise = (configObj.exercises || []).find(
431
+ ex => ex.slug === slug
432
+ )
433
+ if (!exercise)
434
+ throw ValidationError(`Exercise ${slug} not found`)
435
+
436
+ return exercise
437
+ },
438
+ getAllExercises: () => {
439
+ return configObj.exercises
440
+ },
441
+ startExercise: function (slug: string) {
442
+ const exercise = this.getExercise(slug)
443
+
444
+ // set config.json with current exercise
445
+ configObj.currentExercise = exercise.slug
446
+
447
+ this.save()
448
+
449
+ // eslint-disable-next-line
450
+ exercise.files.forEach((f: IFile) => {
451
+ if (configObj.config) {
452
+ const _path = configObj.config.outputPath + "/" + f.name
453
+ if (f.hidden === false && fs.existsSync(_path))
454
+ fs.unlinkSync(_path)
455
+ }
456
+ })
457
+
458
+ return exercise
459
+ },
460
+ noCurrentExercise: function () {
461
+ configObj.currentExercise = null
462
+ this.save()
463
+ },
464
+ reset: slug => {
465
+ if (
466
+ configObj.config &&
467
+ !fs.existsSync(`${configObj.config.dirPath}/resets/` + slug)
468
+ )
469
+ throw ValidationError("Could not find the original files for " + slug)
470
+
471
+ const exercise = (configObj.exercises || []).find(
472
+ ex => ex.slug === slug
473
+ )
474
+ if (!exercise)
475
+ throw ValidationError(`Exercise ${slug} not found on the configuration`)
476
+
477
+ if (configObj.config) {
478
+ for (const fileName of fs.readdirSync(
479
+ `${configObj.config.dirPath}/resets/${slug}/`
480
+ )) {
481
+ const content = fs.readFileSync(
482
+ `${configObj.config?.dirPath}/resets/${slug}/${fileName}`
483
+ )
484
+ fs.writeFileSync(`${exercise.path}/${fileName}`, content)
485
+ }
486
+ }
487
+ },
488
+
489
+ buildIndex: function () {
490
+ Console.info("Building the exercise index...")
491
+
492
+ const isDirectory = (source: string) => {
493
+ const name = path.basename(source)
494
+ if (name === path.basename(configObj?.config?.dirPath || ""))
495
+ return false
496
+ // ignore folders that start with a dot
497
+ if (name.charAt(0) === "." || name.charAt(0) === "_")
498
+ return false
499
+
500
+ return fs.lstatSync(source).isDirectory()
501
+ }
502
+
503
+ const getDirectories = (source: string) =>
504
+ fs
505
+ .readdirSync(source)
506
+ .map(name => path.join(source, name))
507
+ .filter(isDirectory)
508
+ // add the .learn folder
509
+ if (!fs.existsSync(confPath.base))
510
+ fs.mkdirSync(confPath.base)
511
+ // add the outout folder where webpack will publish the the html/css/js files
512
+ if (
513
+ configObj.config &&
514
+ configObj.config.outputPath &&
515
+ !fs.existsSync(configObj.config.outputPath)
516
+ )
517
+ fs.mkdirSync(configObj.config.outputPath)
518
+
519
+ // TODO: we could use npm library front-mater to read the title of the exercises from the README.md
520
+ const grupedByDirectory = getDirectories(
521
+ configObj?.config?.exercisesPath || ""
522
+ )
523
+ configObj.exercises =
524
+ grupedByDirectory.length > 0 ?
525
+ grupedByDirectory.map((path, position) =>
526
+ exercise(path, position, configObj)
527
+ ) :
528
+ [exercise(configObj?.config?.exercisesPath || "", 0, configObj)]
529
+
530
+ if (configObj.config) {
531
+ configObj.config.editor.agent =
532
+ process.env.TERM_PROGRAM === "vscode" ? "vscode" : "os"
533
+ }
534
+
535
+ this.save()
536
+ },
537
+ createExercise: (slug: string, content: string, language: string) => {
538
+ try {
539
+ const dirPath = `${configObj.config?.exercisesPath}/${slug}`
540
+ if (!fs.existsSync(dirPath))
541
+ fs.mkdirSync(dirPath, { recursive: true })
542
+ const isEnglish = language === "us" || language === "en"
543
+ const fileName = isEnglish ? "README.md" : `README.${language}.md`
544
+ fs.writeFileSync(`${dirPath}/${fileName}`, content)
545
+
546
+ return true
547
+ } catch (error) {
548
+ Console.error("Error creating exercise: ", error)
549
+ return false
550
+ }
551
+ },
552
+
553
+ deleteExercise: (slug: string) => {
554
+ const dirPath = `${configObj.config?.exercisesPath}/${slug}`
555
+ if (fs.existsSync(dirPath)) {
556
+ fs.rmSync(dirPath, { recursive: true, force: true })
557
+ return true
558
+ }
559
+
560
+ return false
561
+ },
562
+
563
+ getSidebar: () => {
564
+ const sidebarPath = path.join(
565
+ configObj.config?.dirPath || "",
566
+ "sidebar.json"
567
+ )
568
+ if (fs.existsSync(sidebarPath)) {
569
+ return JSON.parse(fs.readFileSync(sidebarPath, "utf8"))
570
+ }
571
+
572
+ return {}
573
+ },
574
+ watchIndex: function (onChange: (filename: string) => void) {
575
+ if (configObj.config && !configObj.config.exercisesPath)
576
+ throw ValidationError(
577
+ "No exercises directory to watch: " + configObj.config.exercisesPath
578
+ )
579
+
580
+ this.buildIndex()
581
+
582
+ watch(configObj?.config?.exercisesPath || "", onChange)
583
+ .then(() => {
584
+ Console.debug("Changes detected on your exercises")
585
+ this.buildIndex()
586
+ // if (onChange) onChange(filename);
587
+ })
588
+ .catch(error => {
589
+ throw error
590
+ })
591
+ },
592
+
593
+ save: () => {
594
+ Console.debug("Saving configuration with: ", configObj)
595
+ // remove the duplicates form the actions array
596
+ // configObj.config.actions = [...new Set(configObj.config.actions)];
597
+ if (configObj.config) {
598
+ configObj.config.translations = [
599
+ ...new Set(configObj.config.translations),
600
+ ]
601
+ fs.writeFileSync(
602
+ configObj.config.dirPath + "/config.json",
603
+ JSON.stringify(configObj, null, 4)
604
+ )
605
+ }
606
+ },
607
+ } as IConfigManager
608
+ }
609
+
610
+ function deepMerge(...sources: any): any {
611
+ let acc: any = {}
612
+ for (const source of sources) {
613
+ if (Array.isArray(source)) {
614
+ if (!Array.isArray(acc)) {
615
+ acc = []
616
+ }
617
+
618
+ acc = [...source]
619
+ } else if (source instanceof Object) {
620
+ // eslint-disable-next-line
621
+ for (let [key, value] of Object.entries(source)) {
622
+ if (value instanceof Object && key in acc) {
623
+ value = deepMerge(acc[key], value)
624
+ }
625
+
626
+ if (value !== undefined)
627
+ acc = { ...acc, [key]: value }
628
+ }
629
+ }
630
+ }
631
+
632
+ return acc
633
+ }
634
+
635
+ const buildAgentWarning = (current: TAgent, suggested: TAgent): string => {
636
+ const message = `# Agent mismatch!\n
637
+
638
+ In LearnPack, the agent is in charge of running the LearnPack interface.
639
+
640
+ You're currently using LearnPack through \`${current}\` but the suggested agent is \`${suggested}\`.
641
+
642
+ We recommend strongly recommend changing your agent.
643
+
644
+ ${stepsToChangeAgent(suggested)}
645
+ `
646
+
647
+ return message
648
+ }
649
+
650
+ const stepsToChangeAgent = (agent: TAgent): string => {
651
+ if (agent === "vscode") {
652
+ return `
653
+ # Steps to Change Agent to VSCode
654
+
655
+ 1. **Install VSCode**:
656
+ - Visit the [VSCode website](https://code.visualstudio.com/Download) and download the latest version.
657
+ - Follow the installation instructions for your operating system.
658
+
659
+ 2. **Install LearnPack VSCode Extension**:
660
+ - Open VSCode.
661
+ - Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing \`Ctrl+Shift+X\`.
662
+ - Search for "LearnPack" and click "Install".
663
+ - If the extension is already installed but disabled, enable it.
664
+
665
+ 3. **Run LearnPack in VSCode**:
666
+ - Open your terminal in VSCode.
667
+ - Navigate to your LearnPack project directory.
668
+ - Run the following command:
669
+ \`\`\`sh
670
+ learnpack start
671
+ \`\`\`
672
+
673
+ We strongly recommend using VSCode for a better learning experience.
674
+ `
675
+ }
676
+
677
+ if (agent === "os") {
678
+ return `
679
+ # Steps to Change Agent to OS
680
+
681
+ This learning package was designed to run outside of VSCode. We strongly recommend closing VSCode and running the package independently.
682
+
683
+ 1. **Close VSCode**:
684
+ - Save your work and close the VSCode application.
685
+
686
+ 2. **Open a New Terminal**:
687
+ - Open a terminal or command prompt on your operating system.
688
+
689
+ 3. **Navigate to Your LearnPack Project Directory**:
690
+ - Use the \`cd\` command to navigate to the directory where your LearnPack project is located.
691
+
692
+ 4. **Run LearnPack**:
693
+ - Run the following command to start LearnPack:
694
+ \`\`\`sh
695
+ learnpack start
696
+ \`\`\`
697
+
698
+ We strongly recommend running the package independently for a better learning experience.
699
+ `
700
+ }
701
+
702
+ return ""
703
+ }
704
+
705
+ /**
706
+ * Checks if the 'code' command is available in the terminal.
707
+ *
708
+ * @returns {boolean} True if the 'code' command is available, false otherwise.
709
+ */
710
+ const isCodeCommandAvailable = (): boolean => {
711
+ return shell.which("code") !== null
712
+ }
713
+
714
+ /**
715
+ * Checks if a specific VSCode extension is installed.
716
+ *
717
+ * @param {string} extensionName - The name of the extension to check.
718
+ * @returns {boolean} True if the extension is installed, false otherwise.
719
+ */
720
+ const isExtensionInstalled = (extensionName: string): boolean => {
721
+ if (!isCodeCommandAvailable()) {
722
+ throw new Error(
723
+ "The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
724
+ )
725
+ }
726
+
727
+ const result = shell.exec("code --list-extensions", { silent: true })
728
+ return result.stdout.split("\n").includes(extensionName)
729
+ }
730
+
731
+ const EXTENSION_INSTALLATION_STEPS = `
732
+ # Steps to Install LearnPack VSCode Extension
733
+
734
+ 1. **Open VSCode**:
735
+ - Launch the Visual Studio Code application on your computer.
736
+
737
+ 2. **Go to Extensions View**:
738
+ - Click on the Extensions icon in the Activity Bar on the side of the window.
739
+ - Alternatively, you can open the Extensions view by pressing \`Ctrl+Shift+X\`.
740
+
741
+ 3. **Search for LearnPack**:
742
+ - In the Extensions view, type "LearnPack" into the search bar.
743
+
744
+ 4. **Install the Extension**:
745
+ - Find the "LearnPack" extension in the search results and click the "Install" button.
746
+ - If the extension is already installed but disabled, click the "Enable" button.
747
+
748
+ 5. **Verify Installation**:
749
+ - Once installed, you can verify the installation by running the following command in the terminal:
750
+ \`\`\`sh
751
+ code --list-extensions | grep learn-pack.learnpack-vscode
752
+ \`\`\`
753
+ - If the extension is listed, it means the installation was successful.
754
+
755
+ We strongly recommend using the LearnPack extension in VSCode for a better learning experience.
756
+ `
757
+
758
+ /**
759
+ * Installs the LearnPack VSCode extension if the 'code' command is available.
760
+ *
761
+ * @param {string} extensionName - The name of the extension to install.
762
+ * @returns {boolean} True if the installation was successful, false otherwise.
763
+ */
764
+ const installExtension = (extensionName: string): boolean => {
765
+ if (!isCodeCommandAvailable()) {
766
+ throw new Error(
767
+ "The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
768
+ )
769
+ }
770
+
771
+ const result = shell.exec(`code --install-extension ${extensionName}`, {
772
+ silent: true,
773
+ })
774
+ return result.code === 0
775
+ }