@exercode/problem-utils 4.3.4 → 4.3.6
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.
- package/dist/cli/checkAllProblems.cjs +1 -1
- package/dist/cli/checkAllProblems.cjs.map +1 -1
- package/dist/cli/checkAllProblems.js +1 -1
- package/dist/cli/checkAllProblems.js.map +1 -1
- package/dist/cli/exercodeProblem.cjs.map +1 -1
- package/dist/cli/exercodeProblem.js.map +1 -1
- package/dist/helpers/checkProblemDirIsolation.cjs.map +1 -1
- package/dist/helpers/checkProblemDirIsolation.js.map +1 -1
- package/dist/helpers/compareExpectedOutputFiles.cjs.map +1 -1
- package/dist/helpers/compareExpectedOutputFiles.js.map +1 -1
- package/dist/helpers/findModelAnswerDirs.cjs.map +1 -1
- package/dist/helpers/findModelAnswerDirs.js.map +1 -1
- package/dist/helpers/javaJudge.cjs.map +1 -1
- package/dist/helpers/javaJudge.js.map +1 -1
- package/dist/helpers/judgeByStaticAnalysis.cjs.map +1 -1
- package/dist/helpers/judgeByStaticAnalysis.js.map +1 -1
- package/dist/helpers/readOutputFiles.cjs.map +1 -1
- package/dist/helpers/readOutputFiles.js.map +1 -1
- package/dist/helpers/resolveCwds.cjs +1 -1
- package/dist/helpers/resolveCwds.cjs.map +1 -1
- package/dist/helpers/resolveCwds.js +1 -1
- package/dist/helpers/resolveCwds.js.map +1 -1
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs.map +1 -1
- package/dist/helpers/runCommandInTemporaryPackageManagerProject.js.map +1 -1
- package/dist/helpers/sourceCodeGrammars.cjs.map +1 -1
- package/dist/helpers/sourceCodeGrammars.js.map +1 -1
- package/dist/helpers/spawnWithLimits.cjs.map +1 -1
- package/dist/helpers/spawnWithLimits.js.map +1 -1
- package/dist/learningMaterial/validateContest.cjs.map +1 -1
- package/dist/learningMaterial/validateContest.js.map +1 -1
- package/dist/learningMaterial/validateCourse.cjs.map +1 -1
- package/dist/learningMaterial/validateCourse.js.map +1 -1
- package/dist/learningMaterial/validateMaterial.cjs.map +1 -1
- package/dist/learningMaterial/validateMaterial.js.map +1 -1
- package/dist/learningMaterial/validateProblem.cjs.map +1 -1
- package/dist/learningMaterial/validateProblem.js.map +1 -1
- package/dist/presets/command.cjs +1 -1
- package/dist/presets/command.cjs.map +1 -1
- package/dist/presets/command.js +1 -1
- package/dist/presets/command.js.map +1 -1
- package/dist/presets/evaluation.cjs +1 -1
- package/dist/presets/evaluation.cjs.map +1 -1
- package/dist/presets/evaluation.js +1 -1
- package/dist/presets/evaluation.js.map +1 -1
- package/dist/presets/guiCommand.cjs.map +1 -1
- package/dist/presets/guiCommand.js.map +1 -1
- package/dist/presets/springBoot.cjs.map +1 -1
- package/dist/presets/springBoot.js.map +1 -1
- package/dist/presets/stdio.cjs.map +1 -1
- package/dist/presets/stdio.js.map +1 -1
- package/dist/presets/tomcat.cjs.map +1 -1
- package/dist/presets/tomcat.js.map +1 -1
- package/package.json +25 -28
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawnWithLimits.js","names":["path","fs","os","childProcess","killGracePeriodMilliseconds","timeCommand","resolveTimeCommand","isTimeCommandAvailable","liveSubprocesses","subprocess","killSubprocessGroup","spawnWithLimits","timeOutput","openUnlinkedFile","detached","boundedCommand","context","command","spawnedCommand","timeLimitMilliseconds","startTimeMilliseconds","stdoutChunks","stderrChunks","outputBytes","timedOut","outputLimitExceeded","wallTimeSeconds","spawnErrorMessage","appendOutputChunk","chunk","remainingBytes","appendedChunk","chunks","timeout","killTimeout","settled","pendingError","closeTimeout","settle","reject","resolve","code","exitSignal","failAfterClose","error","timeResult","parseTimeOutput","readTail","endedByTimeout","status","timeLimitSeconds","signal","hasErrorCode","directory","prefix","file","length","size","maxBytes","buffer","match","content","parseSeconds","text","result"],"sources":["../../src/helpers/spawnWithLimits.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { hasErrorCode } from '@willbooster/shared-lib';\n\nexport interface SpawnWithLimitsResult {\n stdout: string;\n stderr: string;\n status: number | undefined;\n signal: NodeJS.Signals | undefined;\n /** Wall time measured by GNU time, or measured here until the command exited when it produced none. */\n timeSeconds: number;\n /**\n * User plus system CPU time of the command and the descendants it waited for, measured by GNU\n * time, or 0 when it produced no measurement. A run `timeout` ended is measured too, so a caller\n * can tell a program that used up its time limit from one that waited for the CPU.\n */\n cpuTimeSeconds: number;\n /**\n * Peak resident set size measured by GNU time, or 0 when it produced no measurement. GNU time\n * measures its child `timeout` and the descendants it waited for, so the value is at least\n * `timeout`'s own footprint (about 1 MiB), which only shows for the smallest native programs.\n */\n memoryBytes: number;\n /** The note GNU time adds when the command exits abnormally, e.g. `Command terminated by signal 11`. */\n timeCommandMessage: string | undefined;\n timedOut: boolean;\n outputLimitExceeded: boolean;\n}\n\nconst killGracePeriodMilliseconds = 1000;\nconst MIN_TIMEOUT_SECONDS = 0.001;\n// GNU `timeout` exits with 124 after ending a run at its limit, or with 128 + SIGKILL when the run\n// ignored its SIGTERM and it had to be killed after the grace period.\nconst TIMEOUT_EXIT_STATUS = 124;\nconst KILLED_AFTER_TIMEOUT_EXIT_STATUS = 137;\n// GNU time writes its record to a file this process opened and unlinked at once, handed down as fd 3\n// of the command and reopened by GNU time through `/dev/fd`: the command runs as the same OS user,\n// so a record reachable by path could be swapped for a fake or for a FIFO that blocks the read.\nconst TIME_OUTPUT_FD = 3;\n// The command inherits that descriptor too, so only the tail that can hold GNU time's record is read.\nconst TIME_OUTPUT_TAIL_BYTES = 4096;\nconst timeCommand = resolveTimeCommand();\n\n/** Whether GNU time is available, i.e. whether `timeSeconds`, `cpuTimeSeconds`, and `memoryBytes` are measured at all. */\nexport const isTimeCommandAvailable = timeCommand !== undefined;\n\n// The commands run in their own sessions, so they outlive this process unless it ends them itself\n// on the way out (e.g. a preset's SIGINT handler calling `process.exit`).\nconst liveSubprocesses = new Set<childProcess.ChildProcess>();\nprocess.once('exit', () => {\n for (const subprocess of liveSubprocesses) killSubprocessGroup(subprocess, 'SIGKILL');\n});\n\n/**\n * Runs a command in its own process group with `stdin` piped in, killing the whole group once it\n * exceeds the time or output limit, and reports the wall time, CPU time, and peak memory measured\n * by GNU time.\n */\nexport async function spawnWithLimits(\n command: readonly [string, ...string[]],\n context: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n outputLimitBytes: number;\n stdin: string;\n timeLimitSeconds: number;\n }\n): Promise<SpawnWithLimitsResult> {\n const timeOutput = timeCommand === undefined ? undefined : await openUnlinkedFile('exercode-time-');\n try {\n const detached = process.platform !== 'win32';\n // The command runs in its own session so the group kill below cannot hit this process, but that\n // also puts it out of reach of whoever kills this process. GNU `timeout` keeps the run bounded\n // in that case, and it is what normally ends a run at its limit: GNU time wraps it, so a run\n // that hit the limit still gets its CPU time recorded (a group kill from here would take GNU\n // time down with the command), and `--foreground` keeps the command in this group so the kill\n // below still reaches every descendant. The timers below only back `timeout` up. Should this\n // process die first, `timeout` ends the command alone (`--foreground` signals no descendant),\n // an accepted gap: the judge server sweeps every process of the request's sandbox user anyway.\n const boundedCommand: readonly [string, ...string[]] = detached\n ? [\n 'timeout',\n '--foreground',\n '-k',\n String(killGracePeriodMilliseconds / 1000),\n // A zero duration would disable `timeout`; the front matter allows a zero time limit.\n String(Math.max(context.timeLimitSeconds, MIN_TIMEOUT_SECONDS)),\n ...command,\n ]\n : command;\n const spawnedCommand: readonly [string, ...string[]] =\n timeCommand === undefined\n ? boundedCommand\n : [...timeCommand, `--output=/dev/fd/${TIME_OUTPUT_FD}`, ...boundedCommand];\n // `timeout` sends SIGKILL a grace period after its SIGTERM; the timers here fire once even that\n // should have ended the run.\n const timeLimitMilliseconds = detached\n ? context.timeLimitSeconds * 1000 + 2 * killGracePeriodMilliseconds\n : context.timeLimitSeconds * 1000;\n // Monotonic: a wall-clock step must not turn a run `timeout` ended into one that finished in time.\n const startTimeMilliseconds = performance.now();\n // The standard streams are always pipes; the type cannot express that with the extra entry.\n const subprocess = childProcess.spawn(spawnedCommand[0], spawnedCommand.slice(1), {\n cwd: context.cwd,\n detached,\n env: context.env,\n stdio: timeOutput === undefined ? ['pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe', timeOutput.fd],\n }) as childProcess.ChildProcessWithoutNullStreams;\n liveSubprocesses.add(subprocess);\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let outputBytes = 0;\n let timedOut = false;\n let outputLimitExceeded = false;\n let wallTimeSeconds = 0;\n let spawnErrorMessage: string | undefined;\n\n const appendOutputChunk = (chunks: Buffer[], chunk: Buffer): void => {\n if (outputBytes >= context.outputLimitBytes) {\n if (chunk.byteLength > 0) {\n outputLimitExceeded = true;\n killSubprocessGroup(subprocess, 'SIGKILL');\n }\n return;\n }\n\n const remainingBytes = context.outputLimitBytes - outputBytes;\n const appendedChunk = chunk.byteLength > remainingBytes ? chunk.subarray(0, remainingBytes) : chunk;\n chunks.push(appendedChunk);\n outputBytes += appendedChunk.byteLength;\n\n if (chunk.byteLength > remainingBytes) {\n outputLimitExceeded = true;\n killSubprocessGroup(subprocess, 'SIGKILL');\n }\n };\n\n subprocess.stdout.on('data', (chunk: Buffer) => appendOutputChunk(stdoutChunks, chunk));\n subprocess.stderr.on('data', (chunk: Buffer) => appendOutputChunk(stderrChunks, chunk));\n\n const timeout = setTimeout(() => {\n timedOut = true;\n killSubprocessGroup(subprocess, 'SIGTERM');\n }, timeLimitMilliseconds);\n const killTimeout = setTimeout(() => {\n if (timedOut) killSubprocessGroup(subprocess, 'SIGKILL');\n }, timeLimitMilliseconds + killGracePeriodMilliseconds);\n killTimeout.unref();\n\n const { status, signal } = await new Promise<{ status: number | undefined; signal: NodeJS.Signals | undefined }>(\n (resolve, reject) => {\n let settled = false;\n let pendingError: Error | undefined;\n let closeTimeout: NodeJS.Timeout | undefined;\n const settle = (code: number | null | undefined, exitSignal: NodeJS.Signals | null | undefined): void => {\n if (settled) return;\n settled = true;\n clearTimeout(closeTimeout);\n if (pendingError) {\n reject(pendingError);\n return;\n }\n resolve({ status: code ?? undefined, signal: exitSignal ?? undefined });\n };\n const failAfterClose = (error: Error): void => {\n if (settled) return;\n if (subprocess.pid === undefined) {\n // The spawn itself failed, i.e. the head of the chain (GNU time, or `timeout` without\n // it, or the command itself on Windows) or the cwd is missing. A missing judged command\n // is reported as status 127 by the wrapper instead. Report this like a run that produced\n // only this message.\n spawnErrorMessage = error.message;\n settle(undefined, undefined);\n return;\n }\n pendingError = error;\n killSubprocessGroup(subprocess, 'SIGKILL');\n };\n subprocess.on('error', failAfterClose);\n subprocess.stdin.on('error', (error: NodeJS.ErrnoException) => {\n if (error.code !== 'EPIPE') failAfterClose(error);\n });\n subprocess.on('exit', (code, exitSignal) => {\n // The command is gone, so the limit timers must not fire during the grace period below. A\n // descendant that inherited the pipes (e.g. `sleep 1000 &`) would keep them open and hold\n // back 'close' until it ends: kill what is left of the group. A descendant that moved to\n // its own session survives that, so stop waiting for the pipes after the grace period and\n // keep the output read so far.\n clearTimeout(timeout);\n clearTimeout(killTimeout);\n wallTimeSeconds = (performance.now() - startTimeMilliseconds) / 1000;\n killSubprocessGroup(subprocess, 'SIGKILL');\n closeTimeout = setTimeout(() => {\n subprocess.stdout.destroy();\n subprocess.stderr.destroy();\n settle(code, exitSignal);\n }, killGracePeriodMilliseconds);\n });\n subprocess.on('close', settle);\n subprocess.stdin.end(context.stdin);\n }\n ).finally(() => {\n clearTimeout(timeout);\n clearTimeout(killTimeout);\n liveSubprocesses.delete(subprocess);\n });\n\n const timeResult =\n timeOutput === undefined ? undefined : parseTimeOutput(await readTail(timeOutput, TIME_OUTPUT_TAIL_BYTES));\n\n return {\n stdout: Buffer.concat(stdoutChunks).toString(),\n stderr: spawnErrorMessage ?? Buffer.concat(stderrChunks).toString(),\n status,\n signal,\n // GNU time rounds a fast run to 0.00; the wall time until 'exit' stands in for it (never the\n // grace period spent on the pipes afterwards).\n timeSeconds: timeResult?.timeSeconds || wallTimeSeconds,\n cpuTimeSeconds: timeResult?.cpuTimeSeconds ?? 0,\n memoryBytes: timeResult?.memoryBytes ?? 0,\n timeCommandMessage: timeResult?.message,\n timedOut: timedOut || endedByTimeout(status, wallTimeSeconds, context.timeLimitSeconds),\n outputLimitExceeded,\n };\n } finally {\n await timeOutput?.close();\n }\n}\n\n/**\n * Whether `timeout` ended the run: 124 says it did so at the limit, and 137 that the run ignored its\n * SIGTERM and had to be killed after the grace period. A program can exit with either status on its\n * own, so each is trusted only once the wall time reached the moment `timeout` would have produced it.\n */\nfunction endedByTimeout(status: number | undefined, wallTimeSeconds: number, timeLimitSeconds: number): boolean {\n if (status === TIMEOUT_EXIT_STATUS) return wallTimeSeconds >= timeLimitSeconds;\n if (status === KILLED_AFTER_TIMEOUT_EXIT_STATUS) {\n return wallTimeSeconds >= timeLimitSeconds + killGracePeriodMilliseconds / 1000;\n }\n return false;\n}\n\nfunction killSubprocessGroup(subprocess: childProcess.ChildProcess, signal: NodeJS.Signals): void {\n if (subprocess.pid === undefined) return;\n\n try {\n if (process.platform === 'win32') {\n subprocess.kill(signal);\n return;\n }\n process.kill(-subprocess.pid, signal);\n } catch (error) {\n if (!hasErrorCode(error, 'ESRCH') && !hasErrorCode(error, 'EPERM')) throw error;\n }\n}\n\n// The file is unlinked before it is returned, so nothing can reach it by path anymore.\nasync function openUnlinkedFile(prefix: string): Promise<fs.FileHandle> {\n const directory = await fs.mkdtemp(path.join(os.tmpdir(), prefix));\n try {\n return await fs.open(path.join(directory, 'record'), 'wx+', 0o600);\n } finally {\n await fs.rm(directory, { recursive: true, force: true });\n }\n}\n\nasync function readTail(file: fs.FileHandle, maxBytes: number): Promise<string> {\n const { size } = await file.stat();\n const length = Math.min(size, maxBytes);\n const { buffer } = await file.read(Buffer.alloc(length), 0, length, size - length);\n return buffer.toString();\n}\n\n// Empty when the command was killed before GNU time wrote its record.\nfunction parseTimeOutput(\n content: string\n): { timeSeconds: number; cpuTimeSeconds: number; memoryBytes: number; message: string | undefined } | undefined {\n const match = /(?:^|\\n)(\\d+(?:[.,]\\d+)?) (\\d+(?:[.,]\\d+)?) (\\d+(?:[.,]\\d+)?) (\\d+)\\s*$/.exec(content);\n if (!match) return undefined;\n\n return {\n timeSeconds: parseSeconds(match[1]!),\n cpuTimeSeconds: parseSeconds(match[2]!) + parseSeconds(match[3]!),\n memoryBytes: Number(match[4]) * 1024,\n message: content.slice(0, match.index).trim() || undefined,\n };\n}\n\n// GNU time formats its seconds with the locale's decimal separator.\nfunction parseSeconds(text: string): number {\n return Number(text.replace(',', '.'));\n}\n\nfunction resolveTimeCommand(): readonly [string, ...string[]] | undefined {\n const command = os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time';\n const result = childProcess.spawnSync(command, ['--version'], { stdio: 'ignore' });\n if (result.error || result.status !== 0) return undefined;\n\n // Wall seconds, user CPU seconds, system CPU seconds, peak resident set size in KiB.\n return [command, '--format', '%e %U %S %M'];\n}\n"],"mappings":"yKA+BA,MAAMI,EAA8B,IAY9BC,EAAcC,EAAmB,EAG1BC,EAAyBF,IAAgB,IAAA,GAIhDG,kBAAmB,IAAI,IAC7B,QAAQ,KAAK,WAAc,CACzB,IAAK,IAAMC,KAAcD,EAAkBE,EAAoBD,EAAY,SAAS,CACtF,CAAC,EAOD,eAAsBE,EACpB,EACA,EAOgC,CAChC,IAAMC,EAAaP,IAAgB,IAAA,GAAY,IAAA,GAAY,MAAMQ,EAAiB,gBAAgB,EAClG,GAAI,CACF,IAAMC,EAAW,QAAQ,WAAa,QAShCC,EAAiDD,EACnD,CACE,UACA,eACA,KACA,IAEA,OAAO,KAAK,IAAIE,EAAQ,iBAAkB,IAAmB,CAAC,EAC9D,GAAGC,CACL,EACAA,EACEC,EACJb,IAAgB,IAAA,GACZU,EACA,CAAC,GAAGV,EAAa,qBAAsC,GAAGU,CAAc,EAGxEI,EAAwBL,EAC1BE,EAAQ,iBAAmB,IAAO,EAAIZ,EACtCY,EAAQ,iBAAmB,IAEzBI,EAAwB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EAAaF,EAAM,EAAG,EAChE,YAAa,OAAOA,EAAM,EAAE,EAAI,KAChC,QAASC,EAAQ,MAAM,EAAGD,EAAM,KAAK,CAAC,CAAC,KAAK,GAAK,IAAA,EACnD,CACF,CAGA,SAASE,EAAa,EAAsB,CAC1C,OAAO,OAAOC,EAAK,QAAQ,IAAK,GAAG,CAAC,CACtC,CAEA,SAASzD,GAAiE,CACxE,IAAMW,EAAUf,EAAG,SAAS,IAAM,SAAW,QAAU,gBACjD8D,EAAS7D,EAAa,UAAUc,EAAS,CAAC,WAAW,EAAG,CAAE,MAAO,QAAS,CAAC,EACjF,GAAI,IAAO,OAAS+C,EAAO,SAAW,GAGtC,MAAO,CAAC/C,EAAS,WAAY,aAAa,CAC5C"}
|
|
1
|
+
{"version":3,"file":"spawnWithLimits.js","names":["path","fs","os","childProcess","killGracePeriodMilliseconds","timeCommand","resolveTimeCommand","isTimeCommandAvailable","liveSubprocesses","subprocess","killSubprocessGroup","spawnWithLimits","timeOutput","openUnlinkedFile","detached","boundedCommand","context","command","spawnedCommand","timeLimitMilliseconds","startTimeMilliseconds","stdoutChunks","stderrChunks","outputBytes","timedOut","outputLimitExceeded","wallTimeSeconds","spawnErrorMessage","appendOutputChunk","chunk","remainingBytes","appendedChunk","chunks","timeout","killTimeout","settled","pendingError","closeTimeout","settle","reject","resolve","code","exitSignal","failAfterClose","error","timeResult","parseTimeOutput","readTail","endedByTimeout","status","timeLimitSeconds","signal","hasErrorCode","directory","prefix","file","length","size","maxBytes","buffer","match","content","parseSeconds","text","result"],"sources":["../../src/helpers/spawnWithLimits.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { hasErrorCode } from '@willbooster/shared-lib';\n\nexport interface SpawnWithLimitsResult {\n stdout: string;\n stderr: string;\n status: number | undefined;\n signal: NodeJS.Signals | undefined;\n /** Wall time measured by GNU time, or measured here until the command exited when it produced none. */\n timeSeconds: number;\n /**\n * User plus system CPU time of the command and the descendants it waited for, measured by GNU\n * time, or 0 when it produced no measurement. A run `timeout` ended is measured too, so a caller\n * can tell a program that used up its time limit from one that waited for the CPU.\n */\n cpuTimeSeconds: number;\n /**\n * Peak resident set size measured by GNU time, or 0 when it produced no measurement. GNU time\n * measures its child `timeout` and the descendants it waited for, so the value is at least\n * `timeout`'s own footprint (about 1 MiB), which only shows for the smallest native programs.\n */\n memoryBytes: number;\n /** The note GNU time adds when the command exits abnormally, e.g. `Command terminated by signal 11`. */\n timeCommandMessage: string | undefined;\n timedOut: boolean;\n outputLimitExceeded: boolean;\n}\n\nconst killGracePeriodMilliseconds = 1000;\nconst MIN_TIMEOUT_SECONDS = 0.001;\n// GNU `timeout` exits with 124 after ending a run at its limit, or with 128 + SIGKILL when the run\n// ignored its SIGTERM and it had to be killed after the grace period.\nconst TIMEOUT_EXIT_STATUS = 124;\nconst KILLED_AFTER_TIMEOUT_EXIT_STATUS = 137;\n// GNU time writes its record to a file this process opened and unlinked at once, handed down as fd 3\n// of the command and reopened by GNU time through `/dev/fd`: the command runs as the same OS user,\n// so a record reachable by path could be swapped for a fake or for a FIFO that blocks the read.\nconst TIME_OUTPUT_FD = 3;\n// The command inherits that descriptor too, so only the tail that can hold GNU time's record is read.\nconst TIME_OUTPUT_TAIL_BYTES = 4096;\nconst timeCommand = resolveTimeCommand();\n\n/** Whether GNU time is available, i.e. whether `timeSeconds`, `cpuTimeSeconds`, and `memoryBytes` are measured at all. */\nexport const isTimeCommandAvailable = timeCommand !== undefined;\n\n// The commands run in their own sessions, so they outlive this process unless it ends them itself\n// on the way out (e.g. a preset's SIGINT handler calling `process.exit`).\nconst liveSubprocesses = new Set<childProcess.ChildProcess>();\nprocess.once('exit', () => {\n for (const subprocess of liveSubprocesses) killSubprocessGroup(subprocess, 'SIGKILL');\n});\n\n/**\n * Runs a command in its own process group with `stdin` piped in, killing the whole group once it\n * exceeds the time or output limit, and reports the wall time, CPU time, and peak memory measured\n * by GNU time.\n */\nexport async function spawnWithLimits(\n command: readonly [string, ...string[]],\n context: {\n cwd: string;\n env: NodeJS.ProcessEnv;\n outputLimitBytes: number;\n stdin: string;\n timeLimitSeconds: number;\n }\n): Promise<SpawnWithLimitsResult> {\n const timeOutput = timeCommand === undefined ? undefined : await openUnlinkedFile('exercode-time-');\n try {\n const detached = process.platform !== 'win32';\n // The command runs in its own session so the group kill below cannot hit this process, but that\n // also puts it out of reach of whoever kills this process. GNU `timeout` keeps the run bounded\n // in that case, and it is what normally ends a run at its limit: GNU time wraps it, so a run\n // that hit the limit still gets its CPU time recorded (a group kill from here would take GNU\n // time down with the command), and `--foreground` keeps the command in this group so the kill\n // below still reaches every descendant. The timers below only back `timeout` up. Should this\n // process die first, `timeout` ends the command alone (`--foreground` signals no descendant),\n // an accepted gap: the judge server sweeps every process of the request's sandbox user anyway.\n const boundedCommand: readonly [string, ...string[]] = detached\n ? [\n 'timeout',\n '--foreground',\n '-k',\n String(killGracePeriodMilliseconds / 1000),\n // A zero duration would disable `timeout`; the front matter allows a zero time limit.\n String(Math.max(context.timeLimitSeconds, MIN_TIMEOUT_SECONDS)),\n ...command,\n ]\n : command;\n const spawnedCommand: readonly [string, ...string[]] =\n timeCommand === undefined\n ? boundedCommand\n : [...timeCommand, `--output=/dev/fd/${TIME_OUTPUT_FD}`, ...boundedCommand];\n // `timeout` sends SIGKILL a grace period after its SIGTERM; the timers here fire once even that\n // should have ended the run.\n const timeLimitMilliseconds = detached\n ? context.timeLimitSeconds * 1000 + 2 * killGracePeriodMilliseconds\n : context.timeLimitSeconds * 1000;\n // Monotonic: a wall-clock step must not turn a run `timeout` ended into one that finished in time.\n const startTimeMilliseconds = performance.now();\n // The standard streams are always pipes; the type cannot express that with the extra entry.\n const subprocess = childProcess.spawn(spawnedCommand[0], spawnedCommand.slice(1), {\n cwd: context.cwd,\n detached,\n env: context.env,\n stdio: timeOutput === undefined ? ['pipe', 'pipe', 'pipe'] : ['pipe', 'pipe', 'pipe', timeOutput.fd],\n }) as childProcess.ChildProcessWithoutNullStreams;\n liveSubprocesses.add(subprocess);\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let outputBytes = 0;\n let timedOut = false;\n let outputLimitExceeded = false;\n let wallTimeSeconds = 0;\n let spawnErrorMessage: string | undefined;\n\n const appendOutputChunk = (chunks: Buffer[], chunk: Buffer): void => {\n if (outputBytes >= context.outputLimitBytes) {\n if (chunk.byteLength > 0) {\n outputLimitExceeded = true;\n killSubprocessGroup(subprocess, 'SIGKILL');\n }\n return;\n }\n\n const remainingBytes = context.outputLimitBytes - outputBytes;\n const appendedChunk = chunk.byteLength > remainingBytes ? chunk.subarray(0, remainingBytes) : chunk;\n chunks.push(appendedChunk);\n outputBytes += appendedChunk.byteLength;\n\n if (chunk.byteLength > remainingBytes) {\n outputLimitExceeded = true;\n killSubprocessGroup(subprocess, 'SIGKILL');\n }\n };\n\n subprocess.stdout.on('data', (chunk: Buffer) => appendOutputChunk(stdoutChunks, chunk));\n subprocess.stderr.on('data', (chunk: Buffer) => appendOutputChunk(stderrChunks, chunk));\n\n const timeout = setTimeout(() => {\n timedOut = true;\n killSubprocessGroup(subprocess, 'SIGTERM');\n }, timeLimitMilliseconds);\n const killTimeout = setTimeout(() => {\n if (timedOut) killSubprocessGroup(subprocess, 'SIGKILL');\n }, timeLimitMilliseconds + killGracePeriodMilliseconds);\n killTimeout.unref();\n\n const { status, signal } = await new Promise<{ status: number | undefined; signal: NodeJS.Signals | undefined }>(\n (resolve, reject) => {\n let settled = false;\n let pendingError: Error | undefined;\n let closeTimeout: NodeJS.Timeout | undefined;\n const settle = (code: number | null | undefined, exitSignal: NodeJS.Signals | null | undefined): void => {\n if (settled) return;\n settled = true;\n clearTimeout(closeTimeout);\n if (pendingError) {\n reject(pendingError);\n return;\n }\n resolve({ status: code ?? undefined, signal: exitSignal ?? undefined });\n };\n const failAfterClose = (error: Error): void => {\n if (settled) return;\n if (subprocess.pid === undefined) {\n // The spawn itself failed, i.e. the head of the chain (GNU time, or `timeout` without\n // it, or the command itself on Windows) or the cwd is missing. A missing judged command\n // is reported as status 127 by the wrapper instead. Report this like a run that produced\n // only this message.\n spawnErrorMessage = error.message;\n settle(undefined, undefined);\n return;\n }\n pendingError = error;\n killSubprocessGroup(subprocess, 'SIGKILL');\n };\n subprocess.on('error', failAfterClose);\n subprocess.stdin.on('error', (error: NodeJS.ErrnoException) => {\n if (error.code !== 'EPIPE') failAfterClose(error);\n });\n subprocess.on('exit', (code, exitSignal) => {\n // The command is gone, so the limit timers must not fire during the grace period below. A\n // descendant that inherited the pipes (e.g. `sleep 1000 &`) would keep them open and hold\n // back 'close' until it ends: kill what is left of the group. A descendant that moved to\n // its own session survives that, so stop waiting for the pipes after the grace period and\n // keep the output read so far.\n clearTimeout(timeout);\n clearTimeout(killTimeout);\n wallTimeSeconds = (performance.now() - startTimeMilliseconds) / 1000;\n killSubprocessGroup(subprocess, 'SIGKILL');\n closeTimeout = setTimeout(() => {\n subprocess.stdout.destroy();\n subprocess.stderr.destroy();\n settle(code, exitSignal);\n }, killGracePeriodMilliseconds);\n });\n subprocess.on('close', settle);\n subprocess.stdin.end(context.stdin);\n }\n ).finally(() => {\n clearTimeout(timeout);\n clearTimeout(killTimeout);\n liveSubprocesses.delete(subprocess);\n });\n\n const timeResult =\n timeOutput === undefined ? undefined : parseTimeOutput(await readTail(timeOutput, TIME_OUTPUT_TAIL_BYTES));\n\n return {\n stdout: Buffer.concat(stdoutChunks).toString(),\n stderr: spawnErrorMessage ?? Buffer.concat(stderrChunks).toString(),\n status,\n signal,\n // GNU time rounds a fast run to 0.00; the wall time until 'exit' stands in for it (never the\n // grace period spent on the pipes afterwards).\n timeSeconds: timeResult?.timeSeconds || wallTimeSeconds,\n cpuTimeSeconds: timeResult?.cpuTimeSeconds ?? 0,\n memoryBytes: timeResult?.memoryBytes ?? 0,\n timeCommandMessage: timeResult?.message,\n timedOut: timedOut || endedByTimeout(status, wallTimeSeconds, context.timeLimitSeconds),\n outputLimitExceeded,\n };\n } finally {\n await timeOutput?.close();\n }\n}\n\n/**\n * Whether `timeout` ended the run: 124 says it did so at the limit, and 137 that the run ignored its\n * SIGTERM and had to be killed after the grace period. A program can exit with either status on its\n * own, so each is trusted only once the wall time reached the moment `timeout` would have produced it.\n */\nfunction endedByTimeout(status: number | undefined, wallTimeSeconds: number, timeLimitSeconds: number): boolean {\n if (status === TIMEOUT_EXIT_STATUS) return wallTimeSeconds >= timeLimitSeconds;\n if (status === KILLED_AFTER_TIMEOUT_EXIT_STATUS) {\n return wallTimeSeconds >= timeLimitSeconds + killGracePeriodMilliseconds / 1000;\n }\n return false;\n}\n\nfunction killSubprocessGroup(subprocess: childProcess.ChildProcess, signal: NodeJS.Signals): void {\n if (subprocess.pid === undefined) return;\n\n try {\n if (process.platform === 'win32') {\n subprocess.kill(signal);\n return;\n }\n process.kill(-subprocess.pid, signal);\n } catch (error) {\n if (!hasErrorCode(error, 'ESRCH') && !hasErrorCode(error, 'EPERM')) throw error;\n }\n}\n\n// The file is unlinked before it is returned, so nothing can reach it by path anymore.\nasync function openUnlinkedFile(prefix: string): Promise<fs.FileHandle> {\n const directory = await fs.mkdtemp(path.join(os.tmpdir(), prefix));\n try {\n return await fs.open(path.join(directory, 'record'), 'wx+', 0o600);\n } finally {\n await fs.rm(directory, { recursive: true, force: true });\n }\n}\n\nasync function readTail(file: fs.FileHandle, maxBytes: number): Promise<string> {\n const { size } = await file.stat();\n const length = Math.min(size, maxBytes);\n const { buffer } = await file.read(Buffer.alloc(length), 0, length, size - length);\n return buffer.toString();\n}\n\n// Empty when the command was killed before GNU time wrote its record.\nfunction parseTimeOutput(\n content: string\n): { timeSeconds: number; cpuTimeSeconds: number; memoryBytes: number; message: string | undefined } | undefined {\n const match = /(?:^|\\n)(\\d+(?:[.,]\\d+)?) (\\d+(?:[.,]\\d+)?) (\\d+(?:[.,]\\d+)?) (\\d+)\\s*$/.exec(content);\n if (!match) return undefined;\n\n return {\n timeSeconds: parseSeconds(match[1]!),\n cpuTimeSeconds: parseSeconds(match[2]!) + parseSeconds(match[3]!),\n memoryBytes: Number(match[4]) * 1024,\n message: content.slice(0, match.index).trim() || undefined,\n };\n}\n\n// GNU time formats its seconds with the locale's decimal separator.\nfunction parseSeconds(text: string): number {\n return Number(text.replace(',', '.'));\n}\n\nfunction resolveTimeCommand(): readonly [string, ...string[]] | undefined {\n const command = os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time';\n const result = childProcess.spawnSync(command, ['--version'], { stdio: 'ignore' });\n if (result.error || result.status !== 0) return undefined;\n\n // Wall seconds, user CPU seconds, system CPU seconds, peak resident set size in KiB.\n return [command, '--format', '%e %U %S %M'];\n}\n"],"mappings":"yKAgCA,MAAMI,EAA8B,IAY9BC,EAAcC,EAAmB,EAG1BC,EAAyBF,IAAgB,IAAA,GAIhDG,kBAAmB,IAAI,IAC7B,QAAQ,KAAK,WAAc,CACzB,IAAK,IAAMC,KAAcD,EAAkBE,EAAoBD,EAAY,SAAS,CACtF,CAAC,EAOD,eAAsBE,EACpB,EACA,EAOgC,CAChC,IAAMC,EAAaP,IAAgB,IAAA,GAAY,IAAA,GAAY,MAAMQ,EAAiB,gBAAgB,EAClG,GAAI,CACF,IAAMC,EAAW,QAAQ,WAAa,QAShCC,EAAiDD,EACnD,CACE,UACA,eACA,KACA,IAEA,OAAO,KAAK,IAAIE,EAAQ,iBAAkB,IAAmB,CAAC,EAC9D,GAAGC,CACL,EACAA,EACEC,EACJb,IAAgB,IAAA,GACZU,EACA,CAAC,GAAGV,EAAa,qBAAsC,GAAGU,CAAc,EAGxEI,EAAwBL,EAC1BE,EAAQ,iBAAmB,IAAO,EAAIZ,EACtCY,EAAQ,iBAAmB,IAEzBI,EAAwB,YAAY,IAAI,EAExCX,EAAaN,EAAa,MAAMe,EAAe,GAAIA,EAAe,MAAM,CAAC,EAAG,CAChF,IAAKF,EAAQ,IACb,WACA,IAAKA,EAAQ,IACb,MAAOJ,IAAe,IAAA,GAAY,CAAC,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EAAsB,CAC1C,OAAO,OAAOC,EAAK,QAAQ,IAAK,GAAG,CAAC,CACtC,CAEA,SAASzD,GAAiE,CACxE,IAAMW,EAAUf,EAAG,SAAS,IAAM,SAAW,QAAU,gBACjD8D,EAAS7D,EAAa,UAAUc,EAAS,CAAC,WAAW,EAAG,CAAE,MAAO,QAAS,CAAC,EACjF,GAAI,IAAO,OAAS+C,EAAO,SAAW,GAGtC,MAAO,CAAC/C,EAAS,WAAY,aAAa,CAC5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateContest.cjs","names":["isRegularFile","isFile","basename","CONTEST_MATERIAL_FILE_SUFFIX","LEARNING_MATERIAL_ID_REGEX","parseYaml","readFile","getErrorMessage","contestFileSchema","formatZodIssues","mergeSubmissionPeriods","collectProblemIdsFromDirectory","require_schemas","require_fsHelpers","require_validationResult","require_validateMaterial","node_path","node_fs_promises","_willbooster_shared_lib","yaml","validateContestFile","errors","warnings","result","contestFilePath","fileName","contestId","rawContent","error","parsed","options","division","problem","availableProblemIds"],"sources":["../../src/learningMaterial/validateContest.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\nimport { collectProblemIdsFromDirectory, isFile, isRegularFile, reportDanglingProblemReferences } from './fsHelpers.js';\nimport { CONTEST_MATERIAL_FILE_SUFFIX, contestFileSchema, LEARNING_MATERIAL_ID_REGEX } from './schemas.js';\nimport {\n mergeSubmissionPeriods,\n reportForeignProblemCourseIds,\n
|
|
1
|
+
{"version":3,"file":"validateContest.cjs","names":["isRegularFile","isFile","basename","CONTEST_MATERIAL_FILE_SUFFIX","LEARNING_MATERIAL_ID_REGEX","parseYaml","readFile","getErrorMessage","contestFileSchema","formatZodIssues","mergeSubmissionPeriods","collectProblemIdsFromDirectory","require_schemas","require_fsHelpers","require_validationResult","require_validateMaterial","node_path","node_fs_promises","_willbooster_shared_lib","yaml","validateContestFile","errors","warnings","result","contestFilePath","fileName","contestId","rawContent","error","parsed","options","division","problem","availableProblemIds"],"sources":["../../src/learningMaterial/validateContest.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\n\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\n\nimport { collectProblemIdsFromDirectory, isFile, isRegularFile, reportDanglingProblemReferences } from './fsHelpers.js';\nimport { CONTEST_MATERIAL_FILE_SUFFIX, contestFileSchema, LEARNING_MATERIAL_ID_REGEX } from './schemas.js';\nimport {\n mergeSubmissionPeriods,\n reportForeignProblemCourseIds,\n type SubmissionPeriods,\n validateSubmissionPeriods,\n} from './validateMaterial.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\nexport interface ContestValidationOptions {\n /** When set, every contest problem ID must be a problem discovered under this path. */\n problemsDirectoryPath?: string;\n /** Problem IDs already collected for the enclosing course; collected from `problemsDirectoryPath` otherwise. */\n availableProblemIds?: ReadonlySet<string>;\n /** Enclosing course ID; the judge rejects problem references whose `courseId` differs from it. */\n courseId?: string;\n /** Course-level submission periods; the judge merges them as `material[field] ?? course[field]`. */\n courseSubmissionPeriods?: SubmissionPeriods;\n /** Set by course validation, which already warns once about a missing problems directory. */\n isNestedInCourse?: boolean;\n}\n\n/** Validates a judge contest material (`*.contest.yaml`) file. */\nexport async function validateContestFile(\n contestFilePath: string,\n options: ContestValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n // The judge lists lecture entries as regular files, so a symbolic link is skipped at import time.\n if (!(await isRegularFile(contestFilePath))) {\n errors.push(\n (await isFile(contestFilePath))\n ? `contest file is a symbolic link, which the judge ignores; commit a regular file: ${contestFilePath}`\n : `contest file not found: ${contestFilePath}`\n );\n return result;\n }\n const fileName = basename(contestFilePath);\n if (!fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX)) {\n errors.push(`contest file name must end with ${CONTEST_MATERIAL_FILE_SUFFIX}: ${fileName}`);\n return result;\n }\n const contestId = fileName.slice(0, -CONTEST_MATERIAL_FILE_SUFFIX.length);\n if (!LEARNING_MATERIAL_ID_REGEX.test(contestId)) {\n errors.push(\n `contest ID \"${contestId}\" (file name without ${CONTEST_MATERIAL_FILE_SUFFIX}) must match ${LEARNING_MATERIAL_ID_REGEX}`\n );\n }\n\n let rawContent: unknown;\n try {\n rawContent = parseYaml(await readFile(contestFilePath, 'utf8'));\n } catch (error) {\n errors.push(`invalid YAML: ${getErrorMessage(error)}`);\n return result;\n }\n const parsed = contestFileSchema.safeParse(rawContent);\n if (!parsed.success) {\n errors.push(...formatZodIssues(parsed.error, 'contest'));\n return result;\n }\n\n validateSubmissionPeriods(mergeSubmissionPeriods(parsed.data, options.courseSubmissionPeriods), errors, parsed.data);\n reportForeignProblemCourseIds(parsed.data.problems, options.courseId, errors);\n reportDuplicateIds(\n parsed.data.divisions.map((division) => division.id),\n 'division',\n errors\n );\n reportDuplicateIds(\n parsed.data.problems.map((problem) => problem.id),\n 'problem',\n errors\n );\n\n let availableProblemIds = options.availableProblemIds;\n if (availableProblemIds === undefined) {\n if (options.problemsDirectoryPath === undefined) {\n if (!options.isNestedInCourse) {\n warnings.push('no problems directory given (pass --problems-dir); problem references are not checked');\n }\n } else {\n availableProblemIds = await collectProblemIdsFromDirectory(options.problemsDirectoryPath, errors);\n }\n }\n if (availableProblemIds !== undefined) {\n reportDanglingProblemReferences(\n parsed.data.problems.map((problem) => problem.id),\n availableProblemIds,\n options.problemsDirectoryPath,\n errors\n );\n }\n return result;\n}\n"],"mappings":"mQA8BA,eAAsBoB,EACpB,EACA,EAAoC,CAAC,EACV,CAC3B,IAAMC,EAAmB,CAAC,EACpBC,EAAqB,CAAC,EACtBC,EAAS,CAAE,SAAQ,UAAS,EAGlC,GAAI,CAAE,MAAMvB,EAAAA,cAAcwB,CAAe,EAMvC,OALAH,EAAO,KACJ,MAAMpB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,EAAS,KAAK,uFAAuF,EAGvG,EAAsB,MAAMX,EAAAA,+BAA+BmB,EAAQ,sBAAuBT,CAAM,GAGhGY,IAAwB,IAAA,IAC1BpB,EAAA,gCACEgB,EAAO,KAAK,SAAS,IAAK,GAAYG,EAAQ,EAAE,EAChDC,EACAH,EAAQ,sBACRT,CACF,EAEKE,CACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateContest.js","names":["parseYaml","validateContestFile","errors","warnings","result","isRegularFile","contestFilePath","isFile","fileName","basename","CONTEST_MATERIAL_FILE_SUFFIX","contestId","LEARNING_MATERIAL_ID_REGEX","rawContent","parse","readFile","error","getErrorMessage","parsed","contestFileSchema","formatZodIssues","validateSubmissionPeriods","mergeSubmissionPeriods","options","reportForeignProblemCourseIds","reportDuplicateIds","division","problem","availableProblemIds","collectProblemIdsFromDirectory","reportDanglingProblemReferences"],"sources":["../../src/learningMaterial/validateContest.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\nimport { collectProblemIdsFromDirectory, isFile, isRegularFile, reportDanglingProblemReferences } from './fsHelpers.js';\nimport { CONTEST_MATERIAL_FILE_SUFFIX, contestFileSchema, LEARNING_MATERIAL_ID_REGEX } from './schemas.js';\nimport {\n mergeSubmissionPeriods,\n reportForeignProblemCourseIds,\n
|
|
1
|
+
{"version":3,"file":"validateContest.js","names":["parseYaml","validateContestFile","errors","warnings","result","isRegularFile","contestFilePath","isFile","fileName","basename","CONTEST_MATERIAL_FILE_SUFFIX","contestId","LEARNING_MATERIAL_ID_REGEX","rawContent","parse","readFile","error","getErrorMessage","parsed","contestFileSchema","formatZodIssues","validateSubmissionPeriods","mergeSubmissionPeriods","options","reportForeignProblemCourseIds","reportDuplicateIds","division","problem","availableProblemIds","collectProblemIdsFromDirectory","reportDanglingProblemReferences"],"sources":["../../src/learningMaterial/validateContest.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\n\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\n\nimport { collectProblemIdsFromDirectory, isFile, isRegularFile, reportDanglingProblemReferences } from './fsHelpers.js';\nimport { CONTEST_MATERIAL_FILE_SUFFIX, contestFileSchema, LEARNING_MATERIAL_ID_REGEX } from './schemas.js';\nimport {\n mergeSubmissionPeriods,\n reportForeignProblemCourseIds,\n type SubmissionPeriods,\n validateSubmissionPeriods,\n} from './validateMaterial.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\nexport interface ContestValidationOptions {\n /** When set, every contest problem ID must be a problem discovered under this path. */\n problemsDirectoryPath?: string;\n /** Problem IDs already collected for the enclosing course; collected from `problemsDirectoryPath` otherwise. */\n availableProblemIds?: ReadonlySet<string>;\n /** Enclosing course ID; the judge rejects problem references whose `courseId` differs from it. */\n courseId?: string;\n /** Course-level submission periods; the judge merges them as `material[field] ?? course[field]`. */\n courseSubmissionPeriods?: SubmissionPeriods;\n /** Set by course validation, which already warns once about a missing problems directory. */\n isNestedInCourse?: boolean;\n}\n\n/** Validates a judge contest material (`*.contest.yaml`) file. */\nexport async function validateContestFile(\n contestFilePath: string,\n options: ContestValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n // The judge lists lecture entries as regular files, so a symbolic link is skipped at import time.\n if (!(await isRegularFile(contestFilePath))) {\n errors.push(\n (await isFile(contestFilePath))\n ? `contest file is a symbolic link, which the judge ignores; commit a regular file: ${contestFilePath}`\n : `contest file not found: ${contestFilePath}`\n );\n return result;\n }\n const fileName = basename(contestFilePath);\n if (!fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX)) {\n errors.push(`contest file name must end with ${CONTEST_MATERIAL_FILE_SUFFIX}: ${fileName}`);\n return result;\n }\n const contestId = fileName.slice(0, -CONTEST_MATERIAL_FILE_SUFFIX.length);\n if (!LEARNING_MATERIAL_ID_REGEX.test(contestId)) {\n errors.push(\n `contest ID \"${contestId}\" (file name without ${CONTEST_MATERIAL_FILE_SUFFIX}) must match ${LEARNING_MATERIAL_ID_REGEX}`\n );\n }\n\n let rawContent: unknown;\n try {\n rawContent = parseYaml(await readFile(contestFilePath, 'utf8'));\n } catch (error) {\n errors.push(`invalid YAML: ${getErrorMessage(error)}`);\n return result;\n }\n const parsed = contestFileSchema.safeParse(rawContent);\n if (!parsed.success) {\n errors.push(...formatZodIssues(parsed.error, 'contest'));\n return result;\n }\n\n validateSubmissionPeriods(mergeSubmissionPeriods(parsed.data, options.courseSubmissionPeriods), errors, parsed.data);\n reportForeignProblemCourseIds(parsed.data.problems, options.courseId, errors);\n reportDuplicateIds(\n parsed.data.divisions.map((division) => division.id),\n 'division',\n errors\n );\n reportDuplicateIds(\n parsed.data.problems.map((problem) => problem.id),\n 'problem',\n errors\n );\n\n let availableProblemIds = options.availableProblemIds;\n if (availableProblemIds === undefined) {\n if (options.problemsDirectoryPath === undefined) {\n if (!options.isNestedInCourse) {\n warnings.push('no problems directory given (pass --problems-dir); problem references are not checked');\n }\n } else {\n availableProblemIds = await collectProblemIdsFromDirectory(options.problemsDirectoryPath, errors);\n }\n }\n if (availableProblemIds !== undefined) {\n reportDanglingProblemReferences(\n parsed.data.problems.map((problem) => problem.id),\n availableProblemIds,\n options.problemsDirectoryPath,\n errors\n );\n }\n return result;\n}\n"],"mappings":"gnBA8BA,eAAsBC,EACpB,EACA,EAAoC,CAAC,EACV,CAC3B,IAAMC,EAAmB,CAAC,EACpBC,EAAqB,CAAC,EACtBC,EAAS,CAAE,SAAQ,UAAS,EAGlC,GAAI,CAAE,MAAMC,EAAcC,CAAe,EAMvC,OALAJ,EAAO,KACJ,MAAMK,EAAOD,CAAe,EACzB,oFAAoFA,IACpF,2BAA2BA,GACjC,EACOF,EAET,IAAMI,EAAWC,EAASH,CAAe,EACzC,GAAI,CAACE,EAAS,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LEARNING_MATERIAL_ID_REGEX","join","dirname","readdir","isRegularFile","isFile","parseYaml","readFile","getErrorMessage","courseFileSchema","formatZodIssues","collectProblemDefinitions","isUsableProblemsDirectory","lstat","relative","sep","CONTEST_MATERIAL_FILE_SUFFIX","validateContestFile","validateMaterialFile","require_schemas","require_fsHelpers","require_validationResult","require_validateMaterial","require_validateContest","node_path","node_fs_promises","_willbooster_shared_lib","yaml","validateCourseDirectory","errors","warnings","result","courseDirectoryPath","absoluteDirectoryPath","explicitProblemsDirectoryPath","options","canonicalize","courseId","parsedCourseFile","parseCourseFile","problemsDirectoryPath","availableProblemIds","collectAvailableProblemIds","coursePeriodErrors","courseFile","courseFileName","error","lectures","lecture","validateLectureDirectory","reportOrphanLectureDirectories","absolutePath","path","lectureIds","dirents","dirent","entry","isMaterialFileName","courseFileNames","presentFileNames","fileName","symlinkFileName","findFirst","courseFilePath","rawContent","parsed","item","items","predicate","definitionPathsById","courseProblemsDirectoryPath","namesConventionalDirectory","isSameEntry","isOutsideDirectory","problemsDirectoryOption","path1","path2","stats1","stats2","relativePath","parentPath","lectureDirectoryPath","lectureId","materialIds","fileNames","f1","f2","materialFilePath","materialResult","materialOptions","warning","duplicateMaterialErrors"],"sources":["../../src/learningMaterial/validateCourse.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\nimport {\n collectProblemDefinitions,\n isDirectory,\n isFile,\n isRegularDirectory,\n isRegularFile,\n isUsableProblemsDirectory,\n reportProblemDefinitionIssues,\n} from './fsHelpers.js';\nimport {\n CONTEST_MATERIAL_FILE_SUFFIX,\n courseFileSchema,\n LEARNING_MATERIAL_ID_REGEX,\n type CourseFile,\n} from './schemas.js';\nimport { validateContestFile } from './validateContest.js';\nimport { validateMaterialFile, validateSubmissionPeriods, type MaterialValidationOptions } from './validateMaterial.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\nexport interface CourseValidationOptions {\n /**\n * Optional extra check only: problem references always resolve against the problems discovered\n * inside the course directory, so a given directory must lie inside it (an outside or missing one\n * is an error).\n */\n problemsDirectoryPath?: string;\n}\n\n/** Validates an exercode course directory (course.yaml plus one directory per lecture with material files). */\nexport async function validateCourseDirectory(\n courseDirectoryPath: string,\n options: CourseValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n // Course discovery does not traverse a symbolic link, so a linked course directory is never imported.\n if (!(await isRegularDirectory(resolve(courseDirectoryPath)))) {\n errors.push(\n (await isDirectory(resolve(courseDirectoryPath)))\n ? `course directory is a symbolic link, which the judge does not traverse: ${courseDirectoryPath}`\n : `course directory not found: ${courseDirectoryPath}`\n );\n return result;\n }\n // Canonical paths make the \"inside the course\" comparisons below independent of how the caller\n // spelled either path (e.g. `/var` vs `/private/var` on macOS).\n const absoluteDirectoryPath = await realpath(courseDirectoryPath);\n const explicitProblemsDirectoryPath =\n options.problemsDirectoryPath === undefined ? undefined : await canonicalize(options.problemsDirectoryPath);\n const courseId = basename(absoluteDirectoryPath);\n if (!LEARNING_MATERIAL_ID_REGEX.test(courseId)) {\n errors.push(`course ID \"${courseId}\" (directory name) must match ${LEARNING_MATERIAL_ID_REGEX}`);\n }\n\n const parsedCourseFile = await parseCourseFile(absoluteDirectoryPath, errors);\n // Messages name the course directory because that is what discovery searches (see collectAvailableProblemIds).\n const problemsDirectoryPath = absoluteDirectoryPath;\n const availableProblemIds = await collectAvailableProblemIds(\n absoluteDirectoryPath,\n options.problemsDirectoryPath,\n explicitProblemsDirectoryPath,\n errors\n );\n\n if (!parsedCourseFile) return result;\n const { courseFile, courseFileName } = parsedCourseFile;\n const coursePeriodErrors: string[] = [];\n validateSubmissionPeriods(courseFile, coursePeriodErrors);\n errors.push(...coursePeriodErrors.map((error) => `${courseFileName}: ${error}`));\n // The importer treats a missing `lectures` as an empty list, so a course without lectures imports\n // nothing but is valid.\n const lectures = courseFile.lectures ?? [];\n if (lectures.length === 0) {\n warnings.push(`${courseFileName} declares no lectures, so no materials are imported`);\n }\n reportDuplicateIds(\n lectures.map((lecture) => lecture.id),\n 'lecture',\n errors\n );\n for (const lecture of lectures) {\n await validateLectureDirectory(\n absoluteDirectoryPath,\n { courseId, courseSubmissionPeriods: courseFile, problemsDirectoryPath, availableProblemIds },\n lecture.id,\n errors,\n warnings\n );\n }\n await reportOrphanLectureDirectories(absoluteDirectoryPath, courseFile, courseFileName, warnings);\n return result;\n}\n\n/**\n * Resolves symbolic links (and, on a case-insensitive file system, the casing) of a regular\n * directory; a linked or missing final entry keeps its own name so it can be reported as such,\n * with only its ancestors resolved.\n */\nasync function canonicalize(path: string): Promise<string> {\n const absolutePath = resolve(path);\n if (await isRegularDirectory(absolutePath)) return realpath(absolutePath);\n try {\n return join(await realpath(dirname(absolutePath)), basename(absolutePath));\n } catch {\n return absolutePath;\n }\n}\n\n/** Directories not listed as lectures are never imported, so their materials silently disappear. */\nasync function reportOrphanLectureDirectories(\n courseDirectoryPath: string,\n courseFile: CourseFile,\n courseFileName: string,\n warnings: string[]\n): Promise<void> {\n const lectureIds = new Set((courseFile.lectures ?? []).map((lecture) => lecture.id));\n const dirents = await readdir(courseDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (\n !dirent.isDirectory() ||\n dirent.name.startsWith('.') ||\n lectureIds.has(dirent.name) ||\n dirent.name === 'problems'\n )\n continue;\n // A lecture imports only its direct files, so only a directory that directly holds material files\n // would gain anything from being listed (problems are found at any depth regardless).\n const entries = await readdir(join(courseDirectoryPath, dirent.name), { withFileTypes: true });\n if (!entries.some((entry) => entry.isFile() && isMaterialFileName(entry.name))) continue;\n warnings.push(\n `directory \"${dirent.name}\" is not listed as a lecture in ${courseFileName}, so its materials are not imported`\n );\n }\n}\n\nasync function parseCourseFile(\n courseDirectoryPath: string,\n errors: string[]\n): Promise<{ courseFile: CourseFile; courseFileName: string } | undefined> {\n // The judge discovers courses by `course.yaml` or `course.yml` (rejecting a directory with both)\n // and skips symbolic links.\n const courseFileNames = ['course.yaml', 'course.yml'];\n const presentFileNames: string[] = [];\n for (const fileName of courseFileNames) {\n if (await isRegularFile(join(courseDirectoryPath, fileName))) presentFileNames.push(fileName);\n }\n if (presentFileNames.length > 1) {\n errors.push('both course.yaml and course.yml exist; the judge rejects the conflicting course files');\n return undefined;\n }\n const courseFileName = presentFileNames[0];\n if (courseFileName === undefined) {\n const symlinkFileName = await findFirst(courseFileNames, (fileName) => isFile(join(courseDirectoryPath, fileName)));\n errors.push(\n symlinkFileName === undefined\n ? 'course.yaml not found'\n : `${symlinkFileName} is a symbolic link, which the judge ignores; commit a regular file`\n );\n return undefined;\n }\n const courseFilePath = join(courseDirectoryPath, courseFileName);\n let rawContent: unknown;\n try {\n rawContent = parseYaml(await readFile(courseFilePath, 'utf8'));\n } catch (error) {\n errors.push(`${courseFileName}: invalid YAML: ${getErrorMessage(error)}`);\n return undefined;\n }\n const parsed = courseFileSchema.safeParse(rawContent);\n if (!parsed.success) {\n errors.push(...formatZodIssues(parsed.error, courseFileName));\n return undefined;\n }\n return { courseFile: parsed.data, courseFileName };\n}\n\nasync function findFirst<T>(items: readonly T[], predicate: (item: T) => Promise<boolean>): Promise<T | undefined> {\n for (const item of items) {\n if (await predicate(item)) return item;\n }\n return undefined;\n}\n\nfunction isMaterialFileName(fileName: string): boolean {\n return (\n fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX) ||\n (fileName.endsWith('.md') && fileName !== 'problem.md' && !fileName.endsWith('.problem.md'))\n );\n}\n\n/**\n * The judge scopes every problem inside the course directory (at any depth) to the course, so the\n * course is always searched; an explicit directory must lie inside it.\n */\nasync function collectAvailableProblemIds(\n courseDirectoryPath: string,\n problemsDirectoryOption: string | undefined,\n explicitProblemsDirectoryPath: string | undefined,\n errors: string[]\n): Promise<Set<string>> {\n const definitionPathsById = await collectProblemDefinitions(courseDirectoryPath);\n reportProblemDefinitionIssues(definitionPathsById, errors);\n const availableProblemIds = new Set(definitionPathsById.keys());\n // Discovery does not traverse a symbolic link, so a linked problems directory imports nothing.\n const courseProblemsDirectoryPath = join(courseDirectoryPath, 'problems');\n const namesConventionalDirectory =\n explicitProblemsDirectoryPath !== undefined &&\n (await isSameEntry(explicitProblemsDirectoryPath, courseProblemsDirectoryPath));\n if (namesConventionalDirectory || (await isDirectory(courseProblemsDirectoryPath))) {\n await isUsableProblemsDirectory(courseProblemsDirectoryPath, errors);\n }\n if (explicitProblemsDirectoryPath === undefined || namesConventionalDirectory) return availableProblemIds;\n if (\n (await isUsableProblemsDirectory(explicitProblemsDirectoryPath, errors)) &&\n isOutsideDirectory(courseDirectoryPath, explicitProblemsDirectoryPath)\n ) {\n // Exercode links a material only to problems inside its course, so outside problems never count.\n errors.push(\n `problems directory ${problemsDirectoryOption} is outside the course directory; Exercode links a material only to problems inside the course, so move them under the course`\n );\n }\n return availableProblemIds;\n}\n\n/** Whether two paths name the same directory entry (e.g. differently cased on a case-insensitive file system). */\nasync function isSameEntry(path1: string, path2: string): Promise<boolean> {\n if (path1 === path2) return true;\n try {\n const [stats1, stats2] = await Promise.all([lstat(path1), lstat(path2)]);\n return stats1.dev === stats2.dev && stats1.ino === stats2.ino;\n } catch {\n return false;\n }\n}\n\nfunction isOutsideDirectory(parentPath: string, path: string): boolean {\n const relativePath = relative(parentPath, path);\n return relativePath === '..' || relativePath.startsWith(`..${sep}`);\n}\n\nasync function validateLectureDirectory(\n courseDirectoryPath: string,\n materialOptions: MaterialValidationOptions,\n lectureId: string,\n errors: string[],\n warnings: string[]\n): Promise<void> {\n const lectureDirectoryPath = join(courseDirectoryPath, lectureId);\n // The judge lists lecture entries as regular files and directories, so symbolic links vanish.\n if (!(await isRegularDirectory(lectureDirectoryPath))) {\n errors.push(\n (await isDirectory(lectureDirectoryPath))\n ? `lecture \"${lectureId}\": directory is a symbolic link, which the judge does not traverse`\n : `lecture \"${lectureId}\": directory not found`\n );\n return;\n }\n\n const materialIds: string[] = [];\n const dirents = await readdir(lectureDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (dirent.isSymbolicLink()) {\n errors.push(`${lectureId}/${dirent.name} is a symbolic link, which the judge ignores; commit a regular file`);\n }\n }\n const fileNames = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => dirent.name)\n .toSorted((f1, f2) => f1.localeCompare(f2));\n for (const fileName of fileNames) {\n const materialFilePath = join(lectureDirectoryPath, fileName);\n let materialResult: ValidationResult;\n if (fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX)) {\n materialIds.push(fileName.slice(0, -CONTEST_MATERIAL_FILE_SUFFIX.length));\n materialResult = await validateContestFile(materialFilePath, { ...materialOptions, isNestedInCourse: true });\n } else if (fileName.endsWith('.md')) {\n materialIds.push(fileName.replace(/\\.[^/.]+$/, ''));\n materialResult = await validateMaterialFile(materialFilePath, materialOptions);\n } else {\n continue;\n }\n errors.push(...materialResult.errors.map((error) => `${lectureId}/${fileName}: ${error}`));\n warnings.push(...materialResult.warnings.map((warning) => `${lectureId}/${fileName}: ${warning}`));\n }\n\n if (materialIds.length === 0) {\n warnings.push(`lecture \"${lectureId}\": no material files (*.md or *${CONTEST_MATERIAL_FILE_SUFFIX}) found`);\n }\n // Material IDs only need to be unique per lecture: exercode's import key is\n // `${courseId}.${lectureId}.${materialId}`, so a course-wide check would reject courses\n // that import fine. Scope the report to the lecture so multi-lecture courses point at the\n // right files.\n const duplicateMaterialErrors: string[] = [];\n reportDuplicateIds(materialIds, 'material', duplicateMaterialErrors);\n errors.push(...duplicateMaterialErrors.map((error) => `lecture \"${lectureId}\": ${error}`));\n}\n"],"mappings":"sSAiCA,eAAsBiC,EACpB,EACA,EAAmC,CAAC,EACT,CAC3B,IAAMC,EAAmB,CAAC,EACpBC,EAAqB,CAAC,EACtBC,EAAS,CAAE,SAAQ,UAAS,EAGlC,GAAI,CAAE,MAAMpC,EAA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GAAO,CAAC,CAC3F"}
|
|
1
|
+
{"version":3,"file":"validateCourse.cjs","names":["isRegularDirectory","resolve","isDirectory","realpath","basename","LEARNING_MATERIAL_ID_REGEX","join","dirname","readdir","isRegularFile","isFile","parseYaml","readFile","getErrorMessage","courseFileSchema","formatZodIssues","collectProblemDefinitions","isUsableProblemsDirectory","lstat","relative","sep","CONTEST_MATERIAL_FILE_SUFFIX","validateContestFile","validateMaterialFile","require_schemas","require_fsHelpers","require_validationResult","require_validateMaterial","require_validateContest","node_path","node_fs_promises","_willbooster_shared_lib","yaml","validateCourseDirectory","errors","warnings","result","courseDirectoryPath","absoluteDirectoryPath","explicitProblemsDirectoryPath","options","canonicalize","courseId","parsedCourseFile","parseCourseFile","problemsDirectoryPath","availableProblemIds","collectAvailableProblemIds","coursePeriodErrors","courseFile","courseFileName","error","lectures","lecture","validateLectureDirectory","reportOrphanLectureDirectories","absolutePath","path","lectureIds","dirents","dirent","entry","isMaterialFileName","courseFileNames","presentFileNames","fileName","symlinkFileName","findFirst","courseFilePath","rawContent","parsed","item","items","predicate","definitionPathsById","courseProblemsDirectoryPath","namesConventionalDirectory","isSameEntry","isOutsideDirectory","problemsDirectoryOption","path1","path2","stats1","stats2","relativePath","parentPath","lectureDirectoryPath","lectureId","materialIds","fileNames","f1","f2","materialFilePath","materialResult","materialOptions","warning","duplicateMaterialErrors"],"sources":["../../src/learningMaterial/validateCourse.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\n\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\n\nimport {\n collectProblemDefinitions,\n isDirectory,\n isFile,\n isRegularDirectory,\n isRegularFile,\n isUsableProblemsDirectory,\n reportProblemDefinitionIssues,\n} from './fsHelpers.js';\nimport {\n CONTEST_MATERIAL_FILE_SUFFIX,\n type CourseFile,\n courseFileSchema,\n LEARNING_MATERIAL_ID_REGEX,\n} from './schemas.js';\nimport { validateContestFile } from './validateContest.js';\nimport { type MaterialValidationOptions, validateMaterialFile, validateSubmissionPeriods } from './validateMaterial.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\nexport interface CourseValidationOptions {\n /**\n * Optional extra check only: problem references always resolve against the problems discovered\n * inside the course directory, so a given directory must lie inside it (an outside or missing one\n * is an error).\n */\n problemsDirectoryPath?: string;\n}\n\n/** Validates an exercode course directory (course.yaml plus one directory per lecture with material files). */\nexport async function validateCourseDirectory(\n courseDirectoryPath: string,\n options: CourseValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n // Course discovery does not traverse a symbolic link, so a linked course directory is never imported.\n if (!(await isRegularDirectory(resolve(courseDirectoryPath)))) {\n errors.push(\n (await isDirectory(resolve(courseDirectoryPath)))\n ? `course directory is a symbolic link, which the judge does not traverse: ${courseDirectoryPath}`\n : `course directory not found: ${courseDirectoryPath}`\n );\n return result;\n }\n // Canonical paths make the \"inside the course\" comparisons below independent of how the caller\n // spelled either path (e.g. `/var` vs `/private/var` on macOS).\n const absoluteDirectoryPath = await realpath(courseDirectoryPath);\n const explicitProblemsDirectoryPath =\n options.problemsDirectoryPath === undefined ? undefined : await canonicalize(options.problemsDirectoryPath);\n const courseId = basename(absoluteDirectoryPath);\n if (!LEARNING_MATERIAL_ID_REGEX.test(courseId)) {\n errors.push(`course ID \"${courseId}\" (directory name) must match ${LEARNING_MATERIAL_ID_REGEX}`);\n }\n\n const parsedCourseFile = await parseCourseFile(absoluteDirectoryPath, errors);\n // Messages name the course directory because that is what discovery searches (see collectAvailableProblemIds).\n const problemsDirectoryPath = absoluteDirectoryPath;\n const availableProblemIds = await collectAvailableProblemIds(\n absoluteDirectoryPath,\n options.problemsDirectoryPath,\n explicitProblemsDirectoryPath,\n errors\n );\n\n if (!parsedCourseFile) return result;\n const { courseFile, courseFileName } = parsedCourseFile;\n const coursePeriodErrors: string[] = [];\n validateSubmissionPeriods(courseFile, coursePeriodErrors);\n errors.push(...coursePeriodErrors.map((error) => `${courseFileName}: ${error}`));\n // The importer treats a missing `lectures` as an empty list, so a course without lectures imports\n // nothing but is valid.\n const lectures = courseFile.lectures ?? [];\n if (lectures.length === 0) {\n warnings.push(`${courseFileName} declares no lectures, so no materials are imported`);\n }\n reportDuplicateIds(\n lectures.map((lecture) => lecture.id),\n 'lecture',\n errors\n );\n for (const lecture of lectures) {\n await validateLectureDirectory(\n absoluteDirectoryPath,\n { courseId, courseSubmissionPeriods: courseFile, problemsDirectoryPath, availableProblemIds },\n lecture.id,\n errors,\n warnings\n );\n }\n await reportOrphanLectureDirectories(absoluteDirectoryPath, courseFile, courseFileName, warnings);\n return result;\n}\n\n/**\n * Resolves symbolic links (and, on a case-insensitive file system, the casing) of a regular\n * directory; a linked or missing final entry keeps its own name so it can be reported as such,\n * with only its ancestors resolved.\n */\nasync function canonicalize(path: string): Promise<string> {\n const absolutePath = resolve(path);\n if (await isRegularDirectory(absolutePath)) return realpath(absolutePath);\n try {\n return join(await realpath(dirname(absolutePath)), basename(absolutePath));\n } catch {\n return absolutePath;\n }\n}\n\n/** Directories not listed as lectures are never imported, so their materials silently disappear. */\nasync function reportOrphanLectureDirectories(\n courseDirectoryPath: string,\n courseFile: CourseFile,\n courseFileName: string,\n warnings: string[]\n): Promise<void> {\n const lectureIds = new Set((courseFile.lectures ?? []).map((lecture) => lecture.id));\n const dirents = await readdir(courseDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (\n !dirent.isDirectory() ||\n dirent.name.startsWith('.') ||\n lectureIds.has(dirent.name) ||\n dirent.name === 'problems'\n )\n continue;\n // A lecture imports only its direct files, so only a directory that directly holds material files\n // would gain anything from being listed (problems are found at any depth regardless).\n const entries = await readdir(join(courseDirectoryPath, dirent.name), { withFileTypes: true });\n if (!entries.some((entry) => entry.isFile() && isMaterialFileName(entry.name))) continue;\n warnings.push(\n `directory \"${dirent.name}\" is not listed as a lecture in ${courseFileName}, so its materials are not imported`\n );\n }\n}\n\nasync function parseCourseFile(\n courseDirectoryPath: string,\n errors: string[]\n): Promise<{ courseFile: CourseFile; courseFileName: string } | undefined> {\n // The judge discovers courses by `course.yaml` or `course.yml` (rejecting a directory with both)\n // and skips symbolic links.\n const courseFileNames = ['course.yaml', 'course.yml'];\n const presentFileNames: string[] = [];\n for (const fileName of courseFileNames) {\n if (await isRegularFile(join(courseDirectoryPath, fileName))) presentFileNames.push(fileName);\n }\n if (presentFileNames.length > 1) {\n errors.push('both course.yaml and course.yml exist; the judge rejects the conflicting course files');\n return undefined;\n }\n const courseFileName = presentFileNames[0];\n if (courseFileName === undefined) {\n const symlinkFileName = await findFirst(courseFileNames, (fileName) => isFile(join(courseDirectoryPath, fileName)));\n errors.push(\n symlinkFileName === undefined\n ? 'course.yaml not found'\n : `${symlinkFileName} is a symbolic link, which the judge ignores; commit a regular file`\n );\n return undefined;\n }\n const courseFilePath = join(courseDirectoryPath, courseFileName);\n let rawContent: unknown;\n try {\n rawContent = parseYaml(await readFile(courseFilePath, 'utf8'));\n } catch (error) {\n errors.push(`${courseFileName}: invalid YAML: ${getErrorMessage(error)}`);\n return undefined;\n }\n const parsed = courseFileSchema.safeParse(rawContent);\n if (!parsed.success) {\n errors.push(...formatZodIssues(parsed.error, courseFileName));\n return undefined;\n }\n return { courseFile: parsed.data, courseFileName };\n}\n\nasync function findFirst<T>(items: readonly T[], predicate: (item: T) => Promise<boolean>): Promise<T | undefined> {\n for (const item of items) {\n if (await predicate(item)) return item;\n }\n return undefined;\n}\n\nfunction isMaterialFileName(fileName: string): boolean {\n return (\n fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX) ||\n (fileName.endsWith('.md') && fileName !== 'problem.md' && !fileName.endsWith('.problem.md'))\n );\n}\n\n/**\n * The judge scopes every problem inside the course directory (at any depth) to the course, so the\n * course is always searched; an explicit directory must lie inside it.\n */\nasync function collectAvailableProblemIds(\n courseDirectoryPath: string,\n problemsDirectoryOption: string | undefined,\n explicitProblemsDirectoryPath: string | undefined,\n errors: string[]\n): Promise<Set<string>> {\n const definitionPathsById = await collectProblemDefinitions(courseDirectoryPath);\n reportProblemDefinitionIssues(definitionPathsById, errors);\n const availableProblemIds = new Set(definitionPathsById.keys());\n // Discovery does not traverse a symbolic link, so a linked problems directory imports nothing.\n const courseProblemsDirectoryPath = join(courseDirectoryPath, 'problems');\n const namesConventionalDirectory =\n explicitProblemsDirectoryPath !== undefined &&\n (await isSameEntry(explicitProblemsDirectoryPath, courseProblemsDirectoryPath));\n if (namesConventionalDirectory || (await isDirectory(courseProblemsDirectoryPath))) {\n await isUsableProblemsDirectory(courseProblemsDirectoryPath, errors);\n }\n if (explicitProblemsDirectoryPath === undefined || namesConventionalDirectory) return availableProblemIds;\n if (\n (await isUsableProblemsDirectory(explicitProblemsDirectoryPath, errors)) &&\n isOutsideDirectory(courseDirectoryPath, explicitProblemsDirectoryPath)\n ) {\n // Exercode links a material only to problems inside its course, so outside problems never count.\n errors.push(\n `problems directory ${problemsDirectoryOption} is outside the course directory; Exercode links a material only to problems inside the course, so move them under the course`\n );\n }\n return availableProblemIds;\n}\n\n/** Whether two paths name the same directory entry (e.g. differently cased on a case-insensitive file system). */\nasync function isSameEntry(path1: string, path2: string): Promise<boolean> {\n if (path1 === path2) return true;\n try {\n const [stats1, stats2] = await Promise.all([lstat(path1), lstat(path2)]);\n return stats1.dev === stats2.dev && stats1.ino === stats2.ino;\n } catch {\n return false;\n }\n}\n\nfunction isOutsideDirectory(parentPath: string, path: string): boolean {\n const relativePath = relative(parentPath, path);\n return relativePath === '..' || relativePath.startsWith(`..${sep}`);\n}\n\nasync function validateLectureDirectory(\n courseDirectoryPath: string,\n materialOptions: MaterialValidationOptions,\n lectureId: string,\n errors: string[],\n warnings: string[]\n): Promise<void> {\n const lectureDirectoryPath = join(courseDirectoryPath, lectureId);\n // The judge lists lecture entries as regular files and directories, so symbolic links vanish.\n if (!(await isRegularDirectory(lectureDirectoryPath))) {\n errors.push(\n (await isDirectory(lectureDirectoryPath))\n ? `lecture \"${lectureId}\": directory is a symbolic link, which the judge does not traverse`\n : `lecture \"${lectureId}\": directory not found`\n );\n return;\n }\n\n const materialIds: string[] = [];\n const dirents = await readdir(lectureDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (dirent.isSymbolicLink()) {\n errors.push(`${lectureId}/${dirent.name} is a symbolic link, which the judge ignores; commit a regular file`);\n }\n }\n const fileNames = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => dirent.name)\n .toSorted((f1, f2) => f1.localeCompare(f2));\n for (const fileName of fileNames) {\n const materialFilePath = join(lectureDirectoryPath, fileName);\n let materialResult: ValidationResult;\n if (fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX)) {\n materialIds.push(fileName.slice(0, -CONTEST_MATERIAL_FILE_SUFFIX.length));\n materialResult = await validateContestFile(materialFilePath, { ...materialOptions, isNestedInCourse: true });\n } else if (fileName.endsWith('.md')) {\n materialIds.push(fileName.replace(/\\.[^/.]+$/, ''));\n materialResult = await validateMaterialFile(materialFilePath, materialOptions);\n } else {\n continue;\n }\n errors.push(...materialResult.errors.map((error) => `${lectureId}/${fileName}: ${error}`));\n warnings.push(...materialResult.warnings.map((warning) => `${lectureId}/${fileName}: ${warning}`));\n }\n\n if (materialIds.length === 0) {\n warnings.push(`lecture \"${lectureId}\": no material files (*.md or *${CONTEST_MATERIAL_FILE_SUFFIX}) found`);\n }\n // Material IDs only need to be unique per lecture: exercode's import key is\n // `${courseId}.${lectureId}.${materialId}`, so a course-wide check would reject courses\n // that import fine. Scope the report to the lecture so multi-lecture courses point at the\n // right files.\n const duplicateMaterialErrors: string[] = [];\n reportDuplicateIds(materialIds, 'material', duplicateMaterialErrors);\n errors.push(...duplicateMaterialErrors.map((error) => `lecture \"${lectureId}\": ${error}`));\n}\n"],"mappings":"sSAmCA,eAAsBiC,EACpB,EACA,EAAmC,CAAC,EACT,CAC3B,IAAMC,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mB8D,EAAa,WAAYQ,CAAuB,EACnE9D,EAAO,KAAK,GAAG8D,EAAwB,IAAK,GAAU,YAAYT,EAAU,KAAKpC,GAAO,CAAC,CAC3F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateCourse.js","names":["parseYaml","validateCourseDirectory","errors","warnings","result","isRegularDirectory","resolve","courseDirectoryPath","isDirectory","absoluteDirectoryPath","realpath","explicitProblemsDirectoryPath","options","canonicalize","courseId","basename","LEARNING_MATERIAL_ID_REGEX","parsedCourseFile","parseCourseFile","problemsDirectoryPath","availableProblemIds","collectAvailableProblemIds","coursePeriodErrors","validateSubmissionPeriods","courseFile","courseFileName","error","lectures","reportDuplicateIds","lecture","validateLectureDirectory","reportOrphanLectureDirectories","absolutePath","path","join","dirname","lectureIds","dirents","readdir","dirent","entry","isMaterialFileName","courseFileNames","presentFileNames","fileName","isRegularFile","symlinkFileName","findFirst","isFile","courseFilePath","rawContent","parse","readFile","getErrorMessage","parsed","courseFileSchema","formatZodIssues","item","items","predicate","definitionPathsById","collectProblemDefinitions","reportProblemDefinitionIssues","courseProblemsDirectoryPath","namesConventionalDirectory","isSameEntry","isUsableProblemsDirectory","isOutsideDirectory","problemsDirectoryOption","path1","path2","stats1","stats2","lstat","relativePath","relative","parentPath","sep","lectureDirectoryPath","lectureId","materialIds","fileNames","f1","f2","materialFilePath","materialResult","CONTEST_MATERIAL_FILE_SUFFIX","validateContestFile","materialOptions","validateMaterialFile","warning","duplicateMaterialErrors"],"sources":["../../src/learningMaterial/validateCourse.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\nimport {\n collectProblemDefinitions,\n isDirectory,\n isFile,\n isRegularDirectory,\n isRegularFile,\n isUsableProblemsDirectory,\n reportProblemDefinitionIssues,\n} from './fsHelpers.js';\nimport {\n CONTEST_MATERIAL_FILE_SUFFIX,\n courseFileSchema,\n LEARNING_MATERIAL_ID_REGEX,\n type CourseFile,\n} from './schemas.js';\nimport { validateContestFile } from './validateContest.js';\nimport { validateMaterialFile, validateSubmissionPeriods, type MaterialValidationOptions } from './validateMaterial.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\nexport interface CourseValidationOptions {\n /**\n * Optional extra check only: problem references always resolve against the problems discovered\n * inside the course directory, so a given directory must lie inside it (an outside or missing one\n * is an error).\n */\n problemsDirectoryPath?: string;\n}\n\n/** Validates an exercode course directory (course.yaml plus one directory per lecture with material files). */\nexport async function validateCourseDirectory(\n courseDirectoryPath: string,\n options: CourseValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n // Course discovery does not traverse a symbolic link, so a linked course directory is never imported.\n if (!(await isRegularDirectory(resolve(courseDirectoryPath)))) {\n errors.push(\n (await isDirectory(resolve(courseDirectoryPath)))\n ? `course directory is a symbolic link, which the judge does not traverse: ${courseDirectoryPath}`\n : `course directory not found: ${courseDirectoryPath}`\n );\n return result;\n }\n // Canonical paths make the \"inside the course\" comparisons below independent of how the caller\n // spelled either path (e.g. `/var` vs `/private/var` on macOS).\n const absoluteDirectoryPath = await realpath(courseDirectoryPath);\n const explicitProblemsDirectoryPath =\n options.problemsDirectoryPath === undefined ? undefined : await canonicalize(options.problemsDirectoryPath);\n const courseId = basename(absoluteDirectoryPath);\n if (!LEARNING_MATERIAL_ID_REGEX.test(courseId)) {\n errors.push(`course ID \"${courseId}\" (directory name) must match ${LEARNING_MATERIAL_ID_REGEX}`);\n }\n\n const parsedCourseFile = await parseCourseFile(absoluteDirectoryPath, errors);\n // Messages name the course directory because that is what discovery searches (see collectAvailableProblemIds).\n const problemsDirectoryPath = absoluteDirectoryPath;\n const availableProblemIds = await collectAvailableProblemIds(\n absoluteDirectoryPath,\n options.problemsDirectoryPath,\n explicitProblemsDirectoryPath,\n errors\n );\n\n if (!parsedCourseFile) return result;\n const { courseFile, courseFileName } = parsedCourseFile;\n const coursePeriodErrors: string[] = [];\n validateSubmissionPeriods(courseFile, coursePeriodErrors);\n errors.push(...coursePeriodErrors.map((error) => `${courseFileName}: ${error}`));\n // The importer treats a missing `lectures` as an empty list, so a course without lectures imports\n // nothing but is valid.\n const lectures = courseFile.lectures ?? [];\n if (lectures.length === 0) {\n warnings.push(`${courseFileName} declares no lectures, so no materials are imported`);\n }\n reportDuplicateIds(\n lectures.map((lecture) => lecture.id),\n 'lecture',\n errors\n );\n for (const lecture of lectures) {\n await validateLectureDirectory(\n absoluteDirectoryPath,\n { courseId, courseSubmissionPeriods: courseFile, problemsDirectoryPath, availableProblemIds },\n lecture.id,\n errors,\n warnings\n );\n }\n await reportOrphanLectureDirectories(absoluteDirectoryPath, courseFile, courseFileName, warnings);\n return result;\n}\n\n/**\n * Resolves symbolic links (and, on a case-insensitive file system, the casing) of a regular\n * directory; a linked or missing final entry keeps its own name so it can be reported as such,\n * with only its ancestors resolved.\n */\nasync function canonicalize(path: string): Promise<string> {\n const absolutePath = resolve(path);\n if (await isRegularDirectory(absolutePath)) return realpath(absolutePath);\n try {\n return join(await realpath(dirname(absolutePath)), basename(absolutePath));\n } catch {\n return absolutePath;\n }\n}\n\n/** Directories not listed as lectures are never imported, so their materials silently disappear. */\nasync function reportOrphanLectureDirectories(\n courseDirectoryPath: string,\n courseFile: CourseFile,\n courseFileName: string,\n warnings: string[]\n): Promise<void> {\n const lectureIds = new Set((courseFile.lectures ?? []).map((lecture) => lecture.id));\n const dirents = await readdir(courseDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (\n !dirent.isDirectory() ||\n dirent.name.startsWith('.') ||\n lectureIds.has(dirent.name) ||\n dirent.name === 'problems'\n )\n continue;\n // A lecture imports only its direct files, so only a directory that directly holds material files\n // would gain anything from being listed (problems are found at any depth regardless).\n const entries = await readdir(join(courseDirectoryPath, dirent.name), { withFileTypes: true });\n if (!entries.some((entry) => entry.isFile() && isMaterialFileName(entry.name))) continue;\n warnings.push(\n `directory \"${dirent.name}\" is not listed as a lecture in ${courseFileName}, so its materials are not imported`\n );\n }\n}\n\nasync function parseCourseFile(\n courseDirectoryPath: string,\n errors: string[]\n): Promise<{ courseFile: CourseFile; courseFileName: string } | undefined> {\n // The judge discovers courses by `course.yaml` or `course.yml` (rejecting a directory with both)\n // and skips symbolic links.\n const courseFileNames = ['course.yaml', 'course.yml'];\n const presentFileNames: string[] = [];\n for (const fileName of courseFileNames) {\n if (await isRegularFile(join(courseDirectoryPath, fileName))) presentFileNames.push(fileName);\n }\n if (presentFileNames.length > 1) {\n errors.push('both course.yaml and course.yml exist; the judge rejects the conflicting course files');\n return undefined;\n }\n const courseFileName = presentFileNames[0];\n if (courseFileName === undefined) {\n const symlinkFileName = await findFirst(courseFileNames, (fileName) => isFile(join(courseDirectoryPath, fileName)));\n errors.push(\n symlinkFileName === undefined\n ? 'course.yaml not found'\n : `${symlinkFileName} is a symbolic link, which the judge ignores; commit a regular file`\n );\n return undefined;\n }\n const courseFilePath = join(courseDirectoryPath, courseFileName);\n let rawContent: unknown;\n try {\n rawContent = parseYaml(await readFile(courseFilePath, 'utf8'));\n } catch (error) {\n errors.push(`${courseFileName}: invalid YAML: ${getErrorMessage(error)}`);\n return undefined;\n }\n const parsed = courseFileSchema.safeParse(rawContent);\n if (!parsed.success) {\n errors.push(...formatZodIssues(parsed.error, courseFileName));\n return undefined;\n }\n return { courseFile: parsed.data, courseFileName };\n}\n\nasync function findFirst<T>(items: readonly T[], predicate: (item: T) => Promise<boolean>): Promise<T | undefined> {\n for (const item of items) {\n if (await predicate(item)) return item;\n }\n return undefined;\n}\n\nfunction isMaterialFileName(fileName: string): boolean {\n return (\n fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX) ||\n (fileName.endsWith('.md') && fileName !== 'problem.md' && !fileName.endsWith('.problem.md'))\n );\n}\n\n/**\n * The judge scopes every problem inside the course directory (at any depth) to the course, so the\n * course is always searched; an explicit directory must lie inside it.\n */\nasync function collectAvailableProblemIds(\n courseDirectoryPath: string,\n problemsDirectoryOption: string | undefined,\n explicitProblemsDirectoryPath: string | undefined,\n errors: string[]\n): Promise<Set<string>> {\n const definitionPathsById = await collectProblemDefinitions(courseDirectoryPath);\n reportProblemDefinitionIssues(definitionPathsById, errors);\n const availableProblemIds = new Set(definitionPathsById.keys());\n // Discovery does not traverse a symbolic link, so a linked problems directory imports nothing.\n const courseProblemsDirectoryPath = join(courseDirectoryPath, 'problems');\n const namesConventionalDirectory =\n explicitProblemsDirectoryPath !== undefined &&\n (await isSameEntry(explicitProblemsDirectoryPath, courseProblemsDirectoryPath));\n if (namesConventionalDirectory || (await isDirectory(courseProblemsDirectoryPath))) {\n await isUsableProblemsDirectory(courseProblemsDirectoryPath, errors);\n }\n if (explicitProblemsDirectoryPath === undefined || namesConventionalDirectory) return availableProblemIds;\n if (\n (await isUsableProblemsDirectory(explicitProblemsDirectoryPath, errors)) &&\n isOutsideDirectory(courseDirectoryPath, explicitProblemsDirectoryPath)\n ) {\n // Exercode links a material only to problems inside its course, so outside problems never count.\n errors.push(\n `problems directory ${problemsDirectoryOption} is outside the course directory; Exercode links a material only to problems inside the course, so move them under the course`\n );\n }\n return availableProblemIds;\n}\n\n/** Whether two paths name the same directory entry (e.g. differently cased on a case-insensitive file system). */\nasync function isSameEntry(path1: string, path2: string): Promise<boolean> {\n if (path1 === path2) return true;\n try {\n const [stats1, stats2] = await Promise.all([lstat(path1), lstat(path2)]);\n return stats1.dev === stats2.dev && stats1.ino === stats2.ino;\n } catch {\n return false;\n }\n}\n\nfunction isOutsideDirectory(parentPath: string, path: string): boolean {\n const relativePath = relative(parentPath, path);\n return relativePath === '..' || relativePath.startsWith(`..${sep}`);\n}\n\nasync function validateLectureDirectory(\n courseDirectoryPath: string,\n materialOptions: MaterialValidationOptions,\n lectureId: string,\n errors: string[],\n warnings: string[]\n): Promise<void> {\n const lectureDirectoryPath = join(courseDirectoryPath, lectureId);\n // The judge lists lecture entries as regular files and directories, so symbolic links vanish.\n if (!(await isRegularDirectory(lectureDirectoryPath))) {\n errors.push(\n (await isDirectory(lectureDirectoryPath))\n ? `lecture \"${lectureId}\": directory is a symbolic link, which the judge does not traverse`\n : `lecture \"${lectureId}\": directory not found`\n );\n return;\n }\n\n const materialIds: string[] = [];\n const dirents = await readdir(lectureDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (dirent.isSymbolicLink()) {\n errors.push(`${lectureId}/${dirent.name} is a symbolic link, which the judge ignores; commit a regular file`);\n }\n }\n const fileNames = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => dirent.name)\n .toSorted((f1, f2) => f1.localeCompare(f2));\n for (const fileName of fileNames) {\n const materialFilePath = join(lectureDirectoryPath, fileName);\n let materialResult: ValidationResult;\n if (fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX)) {\n materialIds.push(fileName.slice(0, -CONTEST_MATERIAL_FILE_SUFFIX.length));\n materialResult = await validateContestFile(materialFilePath, { ...materialOptions, isNestedInCourse: true });\n } else if (fileName.endsWith('.md')) {\n materialIds.push(fileName.replace(/\\.[^/.]+$/, ''));\n materialResult = await validateMaterialFile(materialFilePath, materialOptions);\n } else {\n continue;\n }\n errors.push(...materialResult.errors.map((error) => `${lectureId}/${fileName}: ${error}`));\n warnings.push(...materialResult.warnings.map((warning) => `${lectureId}/${fileName}: ${warning}`));\n }\n\n if (materialIds.length === 0) {\n warnings.push(`lecture \"${lectureId}\": no material files (*.md or *${CONTEST_MATERIAL_FILE_SUFFIX}) found`);\n }\n // Material IDs only need to be unique per lecture: exercode's import key is\n // `${courseId}.${lectureId}.${materialId}`, so a course-wide check would reject courses\n // that import fine. Scope the report to the lecture so multi-lecture courses point at the\n // right files.\n const duplicateMaterialErrors: string[] = [];\n reportDuplicateIds(materialIds, 'material', duplicateMaterialErrors);\n errors.push(...duplicateMaterialErrors.map((error) => `lecture \"${lectureId}\": ${error}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,CAAC,EACxE,EAAiB,MAAMC,EAAoBH,EAAkB,CAAE,GAAGI,EAAiB,iBAAkB,EAAK,CAAC,OACtG,GAAI5C,EAAS,SAAS,KAAK,EAChCoC,EAAY,KAAKpC,EAAS,QAAQ,YAAa,EAAE,CAAC,EAClD,EAAiB,MAAM6C,EAAqBL,EAAkBI,CAAe,OAE7E,SAEFtF,EAAO,KAAK,GAAGmF,EAAe,OAAO,IAAK,GAAU,GAAGN,EAAU,GAAGnC,EAAS,IAAIlB,GAAO,CAAC,EACzFvB,EAAS,KAAK,GAAGkF,EAAe,SAAS,IAAK,GAAY,GAAGN,EAAU,GAAGnC,EAAS,IAAI8C,GAAS,CAAC,CACnG,CAEIV,EAAY,SAAW,GACzB7E,EAAS,KAAK,YAAY4E,EAAU,iCAAiCO,EAA6B,QAAQ,EAM5G,IAAMK,EAAoC,CAAC,EAC3C/D,EAAmBoD,EAAa,WAAYW,CAAuB,EACnEzF,EAAO,KAAK,GAAGyF,EAAwB,IAAK,GAAU,YAAYZ,EAAU,KAAKrD,GAAO,CAAC,CAC3F"}
|
|
1
|
+
{"version":3,"file":"validateCourse.js","names":["parseYaml","validateCourseDirectory","errors","warnings","result","isRegularDirectory","resolve","courseDirectoryPath","isDirectory","absoluteDirectoryPath","realpath","explicitProblemsDirectoryPath","options","canonicalize","courseId","basename","LEARNING_MATERIAL_ID_REGEX","parsedCourseFile","parseCourseFile","problemsDirectoryPath","availableProblemIds","collectAvailableProblemIds","coursePeriodErrors","validateSubmissionPeriods","courseFile","courseFileName","error","lectures","reportDuplicateIds","lecture","validateLectureDirectory","reportOrphanLectureDirectories","absolutePath","path","join","dirname","lectureIds","dirents","readdir","dirent","entry","isMaterialFileName","courseFileNames","presentFileNames","fileName","isRegularFile","symlinkFileName","findFirst","isFile","courseFilePath","rawContent","parse","readFile","getErrorMessage","parsed","courseFileSchema","formatZodIssues","item","items","predicate","definitionPathsById","collectProblemDefinitions","reportProblemDefinitionIssues","courseProblemsDirectoryPath","namesConventionalDirectory","isSameEntry","isUsableProblemsDirectory","isOutsideDirectory","problemsDirectoryOption","path1","path2","stats1","stats2","lstat","relativePath","relative","parentPath","sep","lectureDirectoryPath","lectureId","materialIds","fileNames","f1","f2","materialFilePath","materialResult","CONTEST_MATERIAL_FILE_SUFFIX","validateContestFile","materialOptions","validateMaterialFile","warning","duplicateMaterialErrors"],"sources":["../../src/learningMaterial/validateCourse.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath } from 'node:fs/promises';\nimport { basename, dirname, join, relative, resolve, sep } from 'node:path';\n\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\n\nimport {\n collectProblemDefinitions,\n isDirectory,\n isFile,\n isRegularDirectory,\n isRegularFile,\n isUsableProblemsDirectory,\n reportProblemDefinitionIssues,\n} from './fsHelpers.js';\nimport {\n CONTEST_MATERIAL_FILE_SUFFIX,\n type CourseFile,\n courseFileSchema,\n LEARNING_MATERIAL_ID_REGEX,\n} from './schemas.js';\nimport { validateContestFile } from './validateContest.js';\nimport { type MaterialValidationOptions, validateMaterialFile, validateSubmissionPeriods } from './validateMaterial.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\nexport interface CourseValidationOptions {\n /**\n * Optional extra check only: problem references always resolve against the problems discovered\n * inside the course directory, so a given directory must lie inside it (an outside or missing one\n * is an error).\n */\n problemsDirectoryPath?: string;\n}\n\n/** Validates an exercode course directory (course.yaml plus one directory per lecture with material files). */\nexport async function validateCourseDirectory(\n courseDirectoryPath: string,\n options: CourseValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n // Course discovery does not traverse a symbolic link, so a linked course directory is never imported.\n if (!(await isRegularDirectory(resolve(courseDirectoryPath)))) {\n errors.push(\n (await isDirectory(resolve(courseDirectoryPath)))\n ? `course directory is a symbolic link, which the judge does not traverse: ${courseDirectoryPath}`\n : `course directory not found: ${courseDirectoryPath}`\n );\n return result;\n }\n // Canonical paths make the \"inside the course\" comparisons below independent of how the caller\n // spelled either path (e.g. `/var` vs `/private/var` on macOS).\n const absoluteDirectoryPath = await realpath(courseDirectoryPath);\n const explicitProblemsDirectoryPath =\n options.problemsDirectoryPath === undefined ? undefined : await canonicalize(options.problemsDirectoryPath);\n const courseId = basename(absoluteDirectoryPath);\n if (!LEARNING_MATERIAL_ID_REGEX.test(courseId)) {\n errors.push(`course ID \"${courseId}\" (directory name) must match ${LEARNING_MATERIAL_ID_REGEX}`);\n }\n\n const parsedCourseFile = await parseCourseFile(absoluteDirectoryPath, errors);\n // Messages name the course directory because that is what discovery searches (see collectAvailableProblemIds).\n const problemsDirectoryPath = absoluteDirectoryPath;\n const availableProblemIds = await collectAvailableProblemIds(\n absoluteDirectoryPath,\n options.problemsDirectoryPath,\n explicitProblemsDirectoryPath,\n errors\n );\n\n if (!parsedCourseFile) return result;\n const { courseFile, courseFileName } = parsedCourseFile;\n const coursePeriodErrors: string[] = [];\n validateSubmissionPeriods(courseFile, coursePeriodErrors);\n errors.push(...coursePeriodErrors.map((error) => `${courseFileName}: ${error}`));\n // The importer treats a missing `lectures` as an empty list, so a course without lectures imports\n // nothing but is valid.\n const lectures = courseFile.lectures ?? [];\n if (lectures.length === 0) {\n warnings.push(`${courseFileName} declares no lectures, so no materials are imported`);\n }\n reportDuplicateIds(\n lectures.map((lecture) => lecture.id),\n 'lecture',\n errors\n );\n for (const lecture of lectures) {\n await validateLectureDirectory(\n absoluteDirectoryPath,\n { courseId, courseSubmissionPeriods: courseFile, problemsDirectoryPath, availableProblemIds },\n lecture.id,\n errors,\n warnings\n );\n }\n await reportOrphanLectureDirectories(absoluteDirectoryPath, courseFile, courseFileName, warnings);\n return result;\n}\n\n/**\n * Resolves symbolic links (and, on a case-insensitive file system, the casing) of a regular\n * directory; a linked or missing final entry keeps its own name so it can be reported as such,\n * with only its ancestors resolved.\n */\nasync function canonicalize(path: string): Promise<string> {\n const absolutePath = resolve(path);\n if (await isRegularDirectory(absolutePath)) return realpath(absolutePath);\n try {\n return join(await realpath(dirname(absolutePath)), basename(absolutePath));\n } catch {\n return absolutePath;\n }\n}\n\n/** Directories not listed as lectures are never imported, so their materials silently disappear. */\nasync function reportOrphanLectureDirectories(\n courseDirectoryPath: string,\n courseFile: CourseFile,\n courseFileName: string,\n warnings: string[]\n): Promise<void> {\n const lectureIds = new Set((courseFile.lectures ?? []).map((lecture) => lecture.id));\n const dirents = await readdir(courseDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (\n !dirent.isDirectory() ||\n dirent.name.startsWith('.') ||\n lectureIds.has(dirent.name) ||\n dirent.name === 'problems'\n )\n continue;\n // A lecture imports only its direct files, so only a directory that directly holds material files\n // would gain anything from being listed (problems are found at any depth regardless).\n const entries = await readdir(join(courseDirectoryPath, dirent.name), { withFileTypes: true });\n if (!entries.some((entry) => entry.isFile() && isMaterialFileName(entry.name))) continue;\n warnings.push(\n `directory \"${dirent.name}\" is not listed as a lecture in ${courseFileName}, so its materials are not imported`\n );\n }\n}\n\nasync function parseCourseFile(\n courseDirectoryPath: string,\n errors: string[]\n): Promise<{ courseFile: CourseFile; courseFileName: string } | undefined> {\n // The judge discovers courses by `course.yaml` or `course.yml` (rejecting a directory with both)\n // and skips symbolic links.\n const courseFileNames = ['course.yaml', 'course.yml'];\n const presentFileNames: string[] = [];\n for (const fileName of courseFileNames) {\n if (await isRegularFile(join(courseDirectoryPath, fileName))) presentFileNames.push(fileName);\n }\n if (presentFileNames.length > 1) {\n errors.push('both course.yaml and course.yml exist; the judge rejects the conflicting course files');\n return undefined;\n }\n const courseFileName = presentFileNames[0];\n if (courseFileName === undefined) {\n const symlinkFileName = await findFirst(courseFileNames, (fileName) => isFile(join(courseDirectoryPath, fileName)));\n errors.push(\n symlinkFileName === undefined\n ? 'course.yaml not found'\n : `${symlinkFileName} is a symbolic link, which the judge ignores; commit a regular file`\n );\n return undefined;\n }\n const courseFilePath = join(courseDirectoryPath, courseFileName);\n let rawContent: unknown;\n try {\n rawContent = parseYaml(await readFile(courseFilePath, 'utf8'));\n } catch (error) {\n errors.push(`${courseFileName}: invalid YAML: ${getErrorMessage(error)}`);\n return undefined;\n }\n const parsed = courseFileSchema.safeParse(rawContent);\n if (!parsed.success) {\n errors.push(...formatZodIssues(parsed.error, courseFileName));\n return undefined;\n }\n return { courseFile: parsed.data, courseFileName };\n}\n\nasync function findFirst<T>(items: readonly T[], predicate: (item: T) => Promise<boolean>): Promise<T | undefined> {\n for (const item of items) {\n if (await predicate(item)) return item;\n }\n return undefined;\n}\n\nfunction isMaterialFileName(fileName: string): boolean {\n return (\n fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX) ||\n (fileName.endsWith('.md') && fileName !== 'problem.md' && !fileName.endsWith('.problem.md'))\n );\n}\n\n/**\n * The judge scopes every problem inside the course directory (at any depth) to the course, so the\n * course is always searched; an explicit directory must lie inside it.\n */\nasync function collectAvailableProblemIds(\n courseDirectoryPath: string,\n problemsDirectoryOption: string | undefined,\n explicitProblemsDirectoryPath: string | undefined,\n errors: string[]\n): Promise<Set<string>> {\n const definitionPathsById = await collectProblemDefinitions(courseDirectoryPath);\n reportProblemDefinitionIssues(definitionPathsById, errors);\n const availableProblemIds = new Set(definitionPathsById.keys());\n // Discovery does not traverse a symbolic link, so a linked problems directory imports nothing.\n const courseProblemsDirectoryPath = join(courseDirectoryPath, 'problems');\n const namesConventionalDirectory =\n explicitProblemsDirectoryPath !== undefined &&\n (await isSameEntry(explicitProblemsDirectoryPath, courseProblemsDirectoryPath));\n if (namesConventionalDirectory || (await isDirectory(courseProblemsDirectoryPath))) {\n await isUsableProblemsDirectory(courseProblemsDirectoryPath, errors);\n }\n if (explicitProblemsDirectoryPath === undefined || namesConventionalDirectory) return availableProblemIds;\n if (\n (await isUsableProblemsDirectory(explicitProblemsDirectoryPath, errors)) &&\n isOutsideDirectory(courseDirectoryPath, explicitProblemsDirectoryPath)\n ) {\n // Exercode links a material only to problems inside its course, so outside problems never count.\n errors.push(\n `problems directory ${problemsDirectoryOption} is outside the course directory; Exercode links a material only to problems inside the course, so move them under the course`\n );\n }\n return availableProblemIds;\n}\n\n/** Whether two paths name the same directory entry (e.g. differently cased on a case-insensitive file system). */\nasync function isSameEntry(path1: string, path2: string): Promise<boolean> {\n if (path1 === path2) return true;\n try {\n const [stats1, stats2] = await Promise.all([lstat(path1), lstat(path2)]);\n return stats1.dev === stats2.dev && stats1.ino === stats2.ino;\n } catch {\n return false;\n }\n}\n\nfunction isOutsideDirectory(parentPath: string, path: string): boolean {\n const relativePath = relative(parentPath, path);\n return relativePath === '..' || relativePath.startsWith(`..${sep}`);\n}\n\nasync function validateLectureDirectory(\n courseDirectoryPath: string,\n materialOptions: MaterialValidationOptions,\n lectureId: string,\n errors: string[],\n warnings: string[]\n): Promise<void> {\n const lectureDirectoryPath = join(courseDirectoryPath, lectureId);\n // The judge lists lecture entries as regular files and directories, so symbolic links vanish.\n if (!(await isRegularDirectory(lectureDirectoryPath))) {\n errors.push(\n (await isDirectory(lectureDirectoryPath))\n ? `lecture \"${lectureId}\": directory is a symbolic link, which the judge does not traverse`\n : `lecture \"${lectureId}\": directory not found`\n );\n return;\n }\n\n const materialIds: string[] = [];\n const dirents = await readdir(lectureDirectoryPath, { withFileTypes: true });\n for (const dirent of dirents) {\n if (dirent.isSymbolicLink()) {\n errors.push(`${lectureId}/${dirent.name} is a symbolic link, which the judge ignores; commit a regular file`);\n }\n }\n const fileNames = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => dirent.name)\n .toSorted((f1, f2) => f1.localeCompare(f2));\n for (const fileName of fileNames) {\n const materialFilePath = join(lectureDirectoryPath, fileName);\n let materialResult: ValidationResult;\n if (fileName.endsWith(CONTEST_MATERIAL_FILE_SUFFIX)) {\n materialIds.push(fileName.slice(0, -CONTEST_MATERIAL_FILE_SUFFIX.length));\n materialResult = await validateContestFile(materialFilePath, { ...materialOptions, isNestedInCourse: true });\n } else if (fileName.endsWith('.md')) {\n materialIds.push(fileName.replace(/\\.[^/.]+$/, ''));\n materialResult = await validateMaterialFile(materialFilePath, materialOptions);\n } else {\n continue;\n }\n errors.push(...materialResult.errors.map((error) => `${lectureId}/${fileName}: ${error}`));\n warnings.push(...materialResult.warnings.map((warning) => `${lectureId}/${fileName}: ${warning}`));\n }\n\n if (materialIds.length === 0) {\n warnings.push(`lecture \"${lectureId}\": no material files (*.md or *${CONTEST_MATERIAL_FILE_SUFFIX}) found`);\n }\n // Material IDs only need to be unique per lecture: exercode's import key is\n // `${courseId}.${lectureId}.${materialId}`, so a course-wide check would reject courses\n // that import fine. Scope the report to the lecture so multi-lecture courses point at the\n // right files.\n const duplicateMaterialErrors: string[] = [];\n reportDuplicateIds(materialIds, 'material', duplicateMaterialErrors);\n errors.push(...duplicateMaterialErrors.map((error) => `lecture \"${lectureId}\": ${error}`));\n}\n"],"mappings":"uyBAmCA,eAAsBC,EACpB,EACA,EAAmC,CAAC,EACT,CAC3B,IAAMC,EAAmB,CAAC,EACpBC,EAAqB,CAAC,EACtBC,EAAS,CAAE,SAAQ,UAAS,EAGlC,GAAI,CAAE,MAAMC,EAAmBC,EAAQC,CAAmB,CAAC,EAMzD,OALAL,EAAO,KACJ,MAAMM,EAAYF,EAAQC,CAAmB,CAAC,EAC3C,2EAA2EA,IAC3E,+BAA+BA,GACrC,EACOH,EAIT,IAAMK,EAAwB,MAAMC,EAASH,CAAmB,EAC1DI,EACJC,EAAQ,wBAA0B,IAAA,GAAY,IAAA,GAAY,MAAMC,EAAaD,EAAQ,qBAAqB,EACtGE,EAAWC,EAASN,CAAqB,EAC1CO,EAA2B,KAAKF,CAAQ,GAC3CZ,EAAO,KAAK,cAAcY,EAAS,gCAAgCE,GAA4B,EAGjG,IAAMC,EAAmB,MAAMC,EAAgBT,EAAuBP,CAAM,EAEtEiB,EAAwBV,EACxBW,EAAsB,MAAMC,EAChCZ,EACAG,EAAQ,sBACRD,EACAT,CACF,EAEA,GAAI,CAACe,EAAkB,O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
-
{"version":3,"file":"validateMaterial.cjs","names":["basename","LEARNING_MATERIAL_ID_REGEX","readFile","parseFrontmatter","getErrorMessage","materialFrontmatterSchema","formatZodIssues","collectProblemIdsFromDirectory","parseYaml","questionInCodeBlockSchema","require_schemas","require_fsHelpers","require_frontmatter","require_validationResult","node_path","node_fs_promises","_willbooster_shared_lib","yaml","QUESTION_CODE_BLOCK_REGEX","QUESTION_CODE_BLOCK_OPENER_REGEX","PROBLEM_LINK_REGEX","TURTLE_GRAPHICS_QUESTION_LINK_REGEX","PROBLEM_ASSIGNMENT_REGEX","QUESTION_LINK_REGEX","TURTLE_GRAPHICS_ASSIGNMENT_REGEX","STANDALONE_CHAT_MARKER_REGEX","validateMaterialFile","errors","result","materialId","materialFilePath","markdown","attributes","body","error","parsedFrontmatter","frontmatter","questionsInCodeBlocks","parseQuestionCodeBlocks","questionBlockIds","question","questions","validateQuestion","bodyWithoutQuestionBlocks","collectLinkedIds","linkedTurtleGraphicsQuestionIds","problemIds","problem","reportForeignProblemCourseIds","options","availableProblemIds","reportExcessChatMarkers","validateSubmissionPeriods","mergeSubmissionPeriods","linkRegex","match","id","own","courseDefaults","chatMarkerCount","courseId","problems","matches","leftoverOpenerCount","blockIndex","yamlText","\"yaml\"","rawQuestion","parsed","isSurvey","answerFieldName","isAnswerDefined","answerIndices","answerIndex","answerPattern","answerRegExp","rawAnswerRegExp","periods","earlierName","laterName","earlierValue","laterValue","ownPeriods"],"sources":["../../src/learningMaterial/validateMaterial.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\nimport { collectProblemIdsFromDirectory, reportDanglingProblemReferences } from './fsHelpers.js';\nimport { parseFrontmatter } from './frontmatter.js';\nimport {\n LEARNING_MATERIAL_ID_REGEX,\n materialFrontmatterSchema,\n questionInCodeBlockSchema,\n type MaterialQuestion,\n} from './schemas.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\n// Same patterns the judge uses to extract embedded questions and problem links from material bodies.\n// The block regex intentionally requires LF line endings and a trailing newline after the closing\n// fence, exactly like the judge parser; blocks it misses are reported by detecting leftover openers.\nconst QUESTION_CODE_BLOCK_REGEX = /(?:^|\\n)(?<fence>`{3,}|~{3,})ya?ml +question\\n(?<yaml>[\\s\\S]+?)\\n\\k<fence>\\n/g;\n// Strictly laxer than the parser regex (tolerates CRLF, indentation, and stray whitespace) so\n// question-looking blocks the judge parser would silently skip surface as leftover openers.\nconst QUESTION_CODE_BLOCK_OPENER_REGEX = /^[ \\t]*(?:`{3,}|~{3,})[ \\t]*ya?ml[ \\t]+question[ \\t]*\\r?$/gm;\nconst PROBLEM_LINK_REGEX = /\\[.*?]\\(problems\\/([0-9_a-z-]+?)\\)/g;\nconst TURTLE_GRAPHICS_QUESTION_LINK_REGEX = /\\[.*?]\\(turtle-graphics-questions\\/([0-9_a-z-]+?)\\)/g;\n// Exercode's duplicate-assignment check scans the body with these patterns, whose link text may\n// span lines (unlike the judge's reference collection above).\nconst PROBLEM_ASSIGNMENT_REGEX = /\\[[^\\]]*]\\(problems\\/([0-9_a-z-]+)\\)/g;\nconst QUESTION_LINK_REGEX = /@\\[question]\\(([0-9_a-z-]+)\\)/g;\nconst TURTLE_GRAPHICS_ASSIGNMENT_REGEX = /\\[[^\\]]*]\\(turtle-graphics-questions\\/([0-9_a-z-]+)\\)/g;\nconst CHAT_MARKER = '<!-- chat -->';\n// exercode only counts the marker when it stands alone on a line, so fenced or inline mentions don't count.\nconst STANDALONE_CHAT_MARKER_REGEX = /(^|\\r?\\n)<!-- chat -->[ \\t]*(?=\\r?\\n|$)/g;\n\nexport interface SubmissionPeriods {\n submissionOpenedAt?: string;\n submissionSoftClosedAt?: string;\n submissionHardClosedAt?: string;\n}\n\nexport interface MaterialValidationOptions {\n /** Problem IDs already collected for the enclosing course; collected from `problemsDirectoryPath` otherwise. */\n availableProblemIds?: ReadonlySet<string>;\n /** When set, every referenced problem ID must be a problem discovered under this path. */\n problemsDirectoryPath?: string;\n /** Enclosing course ID; the judge rejects problem references whose `courseId` differs from it. */\n courseId?: string;\n /** Course-level submission periods; the judge merges them as `material[field] ?? course[field]`. */\n courseSubmissionPeriods?: SubmissionPeriods;\n}\n\n/** Validates an exercode markdown material file (frontmatter, embedded questions, problem references). */\nexport async function validateMaterialFile(\n materialFilePath: string,\n options: MaterialValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n const materialId = basename(materialFilePath).replace(/\\.[^/.]+$/, '');\n if (!LEARNING_MATERIAL_ID_REGEX.test(materialId)) {\n errors.push(`material ID \"${materialId}\" (file name without extension) must match ${LEARNING_MATERIAL_ID_REGEX}`);\n }\n\n let markdown: string;\n try {\n markdown = await readFile(materialFilePath, 'utf8');\n } catch {\n errors.push(`material file not found: ${materialFilePath}`);\n return result;\n }\n\n let attributes: unknown;\n let body: string;\n try {\n ({ attributes, body } = parseFrontmatter(markdown));\n } catch (error) {\n errors.push(`invalid YAML frontmatter: ${getErrorMessage(error)}`);\n return result;\n }\n\n const parsedFrontmatter = materialFrontmatterSchema.safeParse(attributes);\n if (!parsedFrontmatter.success) {\n errors.push(...formatZodIssues(parsedFrontmatter.error, 'frontmatter'));\n }\n const frontmatter = parsedFrontmatter.success ? parsedFrontmatter.data : undefined;\n\n const questionsInCodeBlocks = parseQuestionCodeBlocks(body, errors);\n const questionBlockIds = questionsInCodeBlocks.map((question) => question.id);\n const questions = [...(frontmatter?.questions ?? []), ...questionsInCodeBlocks];\n for (const question of questions) {\n validateQuestion(question, errors);\n }\n reportDuplicateIds(\n questions.map((question) => question.id),\n 'question',\n errors\n );\n // Turtle-graphics links in the body merge into the frontmatter list like problem links do,\n // and exercode rejects duplicates in the merged list; deferred until after the question blocks\n // are removed below so links inside question text don't count.\n\n // Exercode's import validation runs two checks: the body must not link the same problem,\n // question or turtle-graphics question twice (every occurrence of the lax link pattern counts),\n // and the generated reference list (frontmatter entries plus the judge's deduplicated body links)\n // must not repeat an ID. The judge replaces recognized question blocks with @[question](id) links\n // before collecting links, so links that appear only inside question text must not count, while\n // each block counts as one question link next to explicit @[question](id) links.\n const bodyWithoutQuestionBlocks = body.replaceAll(QUESTION_CODE_BLOCK_REGEX, '\\n');\n reportDuplicateIds(\n [...questionBlockIds, ...collectLinkedIds(bodyWithoutQuestionBlocks, QUESTION_LINK_REGEX)],\n 'question link',\n errors\n );\n reportDuplicateIds(collectLinkedIds(bodyWithoutQuestionBlocks, PROBLEM_ASSIGNMENT_REGEX), 'problem link', errors);\n reportDuplicateIds(\n collectLinkedIds(bodyWithoutQuestionBlocks, TURTLE_GRAPHICS_ASSIGNMENT_REGEX),\n 'turtle-graphics question link',\n errors\n );\n const linkedTurtleGraphicsQuestionIds = new Set(\n collectLinkedIds(bodyWithoutQuestionBlocks, TURTLE_GRAPHICS_QUESTION_LINK_REGEX)\n );\n reportDuplicateIds(\n [\n ...(frontmatter?.turtleGraphicsQuestions ?? []).map((question) => question.id),\n ...linkedTurtleGraphicsQuestionIds,\n ],\n 'turtleGraphicsQuestion',\n errors\n );\n // Only the links the judge collects become references, and it deduplicates them before merging.\n const problemIds = [\n ...(frontmatter?.problems ?? []).map((problem) => problem.id),\n ...new Set(collectLinkedIds(bodyWithoutQuestionBlocks, PROBLEM_LINK_REGEX)),\n ];\n reportDuplicateIds(problemIds, 'problem', errors);\n reportForeignProblemCourseIds(frontmatter?.problems ?? [], options.courseId, errors);\n const availableProblemIds =\n options.availableProblemIds ??\n (options.problemsDirectoryPath === undefined\n ? undefined\n : await collectProblemIdsFromDirectory(options.problemsDirectoryPath, errors));\n if (availableProblemIds !== undefined) {\n reportDanglingProblemReferences(problemIds, availableProblemIds, options.problemsDirectoryPath, errors);\n }\n\n reportExcessChatMarkers(body, errors);\n\n if (frontmatter) {\n validateSubmissionPeriods(\n mergeSubmissionPeriods(frontmatter, options.courseSubmissionPeriods),\n errors,\n frontmatter\n );\n }\n return result;\n}\n\nfunction collectLinkedIds(body: string, linkRegex: RegExp): string[] {\n return [...body.matchAll(linkRegex)].map((match) => match[1]).filter((id) => id !== undefined);\n}\n\n/** Applies the judge's course→material config merge (`material[field] ?? course[field]`). */\nexport function mergeSubmissionPeriods(\n own: SubmissionPeriods,\n courseDefaults: SubmissionPeriods | undefined\n): SubmissionPeriods {\n return {\n submissionOpenedAt: own.submissionOpenedAt ?? courseDefaults?.submissionOpenedAt,\n submissionSoftClosedAt: own.submissionSoftClosedAt ?? courseDefaults?.submissionSoftClosedAt,\n submissionHardClosedAt: own.submissionHardClosedAt ?? courseDefaults?.submissionHardClosedAt,\n };\n}\n\n/** exercode rejects more than one standalone chat delimiter line in material and problem bodies. */\nexport function reportExcessChatMarkers(body: string, errors: string[]): void {\n const chatMarkerCount = [...body.matchAll(STANDALONE_CHAT_MARKER_REGEX)].length;\n if (chatMarkerCount > 1) {\n errors.push(`at most one \\`${CHAT_MARKER}\\` marker is allowed, but found ${chatMarkerCount}`);\n }\n}\n\n/** The judge's resolveProblemCourseId throws when a problem reference names a different course. */\nexport function reportForeignProblemCourseIds(\n problems: readonly { id: string; courseId?: string }[],\n courseId: string | undefined,\n errors: string[]\n): void {\n if (courseId === undefined) return;\n for (const problem of problems) {\n if (problem.courseId !== undefined && problem.courseId !== courseId) {\n errors.push(`problem \"${problem.id}\": courseId must be \"${courseId}\" but is \"${problem.courseId}\"`);\n }\n }\n}\n\nfunction parseQuestionCodeBlocks(body: string, errors: string[]): MaterialQuestion[] {\n const questions: MaterialQuestion[] = [];\n const matches = [...body.matchAll(QUESTION_CODE_BLOCK_REGEX)];\n // The judge silently renders unparsed question blocks as plain code blocks, so a block the\n // strict regex misses (CRLF line endings, or no newline after the closing fence) would break\n // in production while looking fine here; flag it instead of validating a lie. Openers inside a\n // recognized block (e.g. an example fence in a question's text) are consumed with that block.\n const leftoverOpenerCount = [\n ...body.replaceAll(QUESTION_CODE_BLOCK_REGEX, '\\n').matchAll(QUESTION_CODE_BLOCK_OPENER_REGEX),\n ].length;\n if (leftoverOpenerCount > 0) {\n errors.push(\n `${leftoverOpenerCount} question code block(s) will not be recognized by the judge parser; separate consecutive question blocks with a blank line, use LF line endings, no indentation or trailing whitespace on the fence line, and end the closing fence with a newline`\n );\n }\n for (const [blockIndex, match] of matches.entries()) {\n const yamlText = match.groups?.['yaml'] ?? '';\n let rawQuestion: unknown;\n try {\n rawQuestion = parseYaml(yamlText);\n } catch (error) {\n errors.push(`question block ${blockIndex + 1}: invalid YAML: ${getErrorMessage(error)}`);\n continue;\n }\n const parsed = questionInCodeBlockSchema.safeParse(rawQuestion);\n if (parsed.success) {\n questions.push(parsed.data);\n } else {\n errors.push(...formatZodIssues(parsed.error, `question block ${blockIndex + 1}`));\n }\n }\n return questions;\n}\n\nfunction validateQuestion(question: MaterialQuestion, errors: string[]): void {\n const isSurvey = question.isSurvey === true;\n const [answerFieldName, isAnswerDefined] =\n question.type === 'select'\n ? (['answerIndex', question.answerIndex !== undefined] as const)\n : question.type === 'select_multiple'\n ? (['answerIndices', question.answerIndices !== undefined] as const)\n : (['answerPattern', question.answerPattern !== undefined] as const);\n if (isSurvey && isAnswerDefined) {\n errors.push(`question ${question.id}: \\`${answerFieldName}\\` must not be set when \\`isSurvey\\` is true`);\n }\n if (!isSurvey && !isAnswerDefined) {\n errors.push(`question ${question.id}: \\`${answerFieldName}\\` is required when \\`isSurvey\\` is not true`);\n }\n\n if (question.type === 'select' || question.type === 'select_multiple') {\n const answerIndices =\n question.type === 'select'\n ? Array.isArray(question.answerIndex)\n ? question.answerIndex\n : question.answerIndex === undefined\n ? []\n : [question.answerIndex]\n : (question.answerIndices ?? []);\n // An empty answer set is broken at runtime (select: never correct; select_multiple: an empty\n // submission grades as correct), and exercode's material editor rejects it as well.\n if (!isSurvey && isAnswerDefined && answerIndices.length === 0) {\n errors.push(`question ${question.id}: \\`${answerFieldName}\\` must contain at least one correct answer`);\n }\n for (const answerIndex of answerIndices) {\n if (!Number.isInteger(answerIndex) || answerIndex < 0 || answerIndex >= question.options.length) {\n errors.push(\n `question ${question.id}: ${answerFieldName} out of bounds: ${answerIndex}; expected 0 <= index < options length ${question.options.length}`\n );\n }\n }\n return;\n }\n\n if (isSurvey || question.answerPattern === undefined) return;\n const answerPattern = question.answerPattern.trim();\n let answerRegExp: RegExp;\n let rawAnswerRegExp: RegExp;\n try {\n answerRegExp = new RegExp(`^(?:${answerPattern})$`);\n // Compiled inside the same guard: a pattern like `a)(b` is valid only once wrapped above,\n // so an unguarded raw compile would crash the CLI instead of reporting an error.\n rawAnswerRegExp = new RegExp(question.answerPattern);\n } catch {\n errors.push(\n `question ${question.id}: \\`answerPattern\\` is not a valid regular expression: ${question.answerPattern}`\n );\n return;\n }\n // Mirrors the judge heuristic: a pattern that doesn't match itself likely uses RegExp syntax,\n // so a modelAnswer is required to prove that some concrete answer is accepted.\n // Like the judge, an empty modelAnswer counts as missing.\n // The judge runs this heuristic on the untrimmed pattern and trims only for the anchored match.\n if (!question.modelAnswer && !rawAnswerRegExp.test(question.answerPattern)) {\n errors.push(`question ${question.id}: \\`answerPattern\\` seems a RegExp but \\`modelAnswer\\` is missing`);\n }\n if (question.modelAnswer && !answerRegExp.test(question.modelAnswer.trim())) {\n errors.push(`question ${question.id}: \\`modelAnswer\\` doesn't match \\`answerPattern\\``);\n }\n}\n\n/**\n * Reports inverted submission periods; shared by material, course.yaml, and contest validation.\n * When `ownPeriods` is given (the merged-values case), pairs whose both values are inherited from\n * the course are skipped: they are the course's mistake and are already reported against\n * course.yaml, so repeating them per material would send agents to files with nothing to fix.\n */\nexport function validateSubmissionPeriods(\n periods: SubmissionPeriods,\n errors: string[],\n ownPeriods: SubmissionPeriods = periods\n): void {\n const pairs = [\n ['submissionOpenedAt', 'submissionSoftClosedAt'],\n ['submissionSoftClosedAt', 'submissionHardClosedAt'],\n ['submissionOpenedAt', 'submissionHardClosedAt'],\n ] as const satisfies readonly (readonly [keyof SubmissionPeriods, keyof SubmissionPeriods])[];\n for (const [earlierName, laterName] of pairs) {\n const earlierValue = periods[earlierName];\n const laterValue = periods[laterName];\n if (earlierValue === undefined || laterValue === undefined) continue;\n if (ownPeriods[earlierName] === undefined && ownPeriods[laterName] === undefined) continue;\n if (new Date(laterValue).getTime() < new Date(earlierValue).getTime()) {\n errors.push(`${earlierName} (${earlierValue}) must be <= ${laterName} (${laterValue})`);\n }\n }\n}\n"],"mappings":"8PAiBA,MAAMkB,EAA4B,gFAG5BC,EAAmC,8DACnCC,EAAqB,sCACrBC,EAAsC,uDAGtCC,EAA2B,wCAC3BC,EAAsB,iCACtBC,EAAmC,yDAGnCC,EAA+B,2CAoBrC,eAAsBC,EACpB,EACA,EAAqC,CAAC,EACX,CAC3B,IAAMC,EAAmB,CAAC,EAEpBC,EAAS,CAAE,SAAQ,SAAA,CAAO,CAAE,EAE5BC,GAAA,EAAa7B,EAAAA,SAAAA,CAAS8B,CAAgB,CAAC,CAAC,QAAQ,YAAa,EAAE,EAChE7B,EAAAA,2BAA2B,KAAK4B,CAAU,GAC7CF,EAAO,KAAK,gBAAgBE,EAAW,6CAA6C5B,EAAAA,4BAA4B,EAGlH,IAAI8B,EACJ,GAAI,CACF,EAAW,MAAA,EAAM7B,EAAAA,SAAAA,CAAS4B,EAAkB,MAAM,CACpD,MAAQ,CAEN,OADAH,EAAO,KAAK,4BAA4BG,GAAkB,EACnDF,CACT,CAEA,IAAII,EACAC,EACJ,GAAI,EACD,sBAAuB9B,EAAAA,iBAAiB4B,CAAQ,EACnD,OAASG,EAAO,CAEd,OADAP,EAAO,KAAK,8BAAA,EAA6BvB,EAAAA,gBAAAA,CAAgB8B,CAAK,GAAG,EAC1DN,CACT,CAEA,IAAMO,EAAoB9B,EAAAA,0BAA0B,UAAU2B,CAAU,EACnEG,EAAkB,SACrBR,EAAO,KAAK,GAAGrB,EAAAA,gBAAgB6B,EAAkB,MAAO,aAAa,CAAC,EAExE,IAAMC,EAAcD,EAAkB,QAAUA,EAA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basename","LEARNING_MATERIAL_ID_REGEX","readFile","parseFrontmatter","getErrorMessage","materialFrontmatterSchema","formatZodIssues","collectProblemIdsFromDirectory","parseYaml","questionInCodeBlockSchema","require_schemas","require_fsHelpers","require_frontmatter","require_validationResult","node_path","node_fs_promises","_willbooster_shared_lib","yaml","QUESTION_CODE_BLOCK_REGEX","QUESTION_CODE_BLOCK_OPENER_REGEX","PROBLEM_LINK_REGEX","TURTLE_GRAPHICS_QUESTION_LINK_REGEX","PROBLEM_ASSIGNMENT_REGEX","QUESTION_LINK_REGEX","TURTLE_GRAPHICS_ASSIGNMENT_REGEX","STANDALONE_CHAT_MARKER_REGEX","validateMaterialFile","errors","result","materialId","materialFilePath","markdown","attributes","body","error","parsedFrontmatter","frontmatter","questionsInCodeBlocks","parseQuestionCodeBlocks","questionBlockIds","question","questions","validateQuestion","bodyWithoutQuestionBlocks","collectLinkedIds","linkedTurtleGraphicsQuestionIds","problemIds","problem","reportForeignProblemCourseIds","options","availableProblemIds","reportExcessChatMarkers","validateSubmissionPeriods","mergeSubmissionPeriods","linkRegex","match","id","own","courseDefaults","chatMarkerCount","courseId","problems","matches","leftoverOpenerCount","blockIndex","yamlText","\"yaml\"","rawQuestion","parsed","isSurvey","answerFieldName","isAnswerDefined","answerIndices","answerIndex","answerPattern","answerRegExp","rawAnswerRegExp","periods","earlierName","laterName","earlierValue","laterValue","ownPeriods"],"sources":["../../src/learningMaterial/validateMaterial.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { basename } from 'node:path';\n\nimport { getErrorMessage } from '@willbooster/shared-lib';\nimport { parse as parseYaml } from 'yaml';\n\nimport { parseFrontmatter } from './frontmatter.js';\nimport { collectProblemIdsFromDirectory, reportDanglingProblemReferences } from './fsHelpers.js';\nimport {\n LEARNING_MATERIAL_ID_REGEX,\n materialFrontmatterSchema,\n type MaterialQuestion,\n questionInCodeBlockSchema,\n} from './schemas.js';\nimport { formatZodIssues, reportDuplicateIds, type ValidationResult } from './validationResult.js';\n\n// Same patterns the judge uses to extract embedded questions and problem links from material bodies.\n// The block regex intentionally requires LF line endings and a trailing newline after the closing\n// fence, exactly like the judge parser; blocks it misses are reported by detecting leftover openers.\nconst QUESTION_CODE_BLOCK_REGEX = /(?:^|\\n)(?<fence>`{3,}|~{3,})ya?ml +question\\n(?<yaml>[\\s\\S]+?)\\n\\k<fence>\\n/g;\n// Strictly laxer than the parser regex (tolerates CRLF, indentation, and stray whitespace) so\n// question-looking blocks the judge parser would silently skip surface as leftover openers.\nconst QUESTION_CODE_BLOCK_OPENER_REGEX = /^[ \\t]*(?:`{3,}|~{3,})[ \\t]*ya?ml[ \\t]+question[ \\t]*\\r?$/gm;\nconst PROBLEM_LINK_REGEX = /\\[.*?]\\(problems\\/([0-9_a-z-]+?)\\)/g;\nconst TURTLE_GRAPHICS_QUESTION_LINK_REGEX = /\\[.*?]\\(turtle-graphics-questions\\/([0-9_a-z-]+?)\\)/g;\n// Exercode's duplicate-assignment check scans the body with these patterns, whose link text may\n// span lines (unlike the judge's reference collection above).\nconst PROBLEM_ASSIGNMENT_REGEX = /\\[[^\\]]*]\\(problems\\/([0-9_a-z-]+)\\)/g;\nconst QUESTION_LINK_REGEX = /@\\[question]\\(([0-9_a-z-]+)\\)/g;\nconst TURTLE_GRAPHICS_ASSIGNMENT_REGEX = /\\[[^\\]]*]\\(turtle-graphics-questions\\/([0-9_a-z-]+)\\)/g;\nconst CHAT_MARKER = '<!-- chat -->';\n// exercode only counts the marker when it stands alone on a line, so fenced or inline mentions don't count.\nconst STANDALONE_CHAT_MARKER_REGEX = /(^|\\r?\\n)<!-- chat -->[ \\t]*(?=\\r?\\n|$)/g;\n\nexport interface SubmissionPeriods {\n submissionOpenedAt?: string;\n submissionSoftClosedAt?: string;\n submissionHardClosedAt?: string;\n}\n\nexport interface MaterialValidationOptions {\n /** Problem IDs already collected for the enclosing course; collected from `problemsDirectoryPath` otherwise. */\n availableProblemIds?: ReadonlySet<string>;\n /** When set, every referenced problem ID must be a problem discovered under this path. */\n problemsDirectoryPath?: string;\n /** Enclosing course ID; the judge rejects problem references whose `courseId` differs from it. */\n courseId?: string;\n /** Course-level submission periods; the judge merges them as `material[field] ?? course[field]`. */\n courseSubmissionPeriods?: SubmissionPeriods;\n}\n\n/** Validates an exercode markdown material file (frontmatter, embedded questions, problem references). */\nexport async function validateMaterialFile(\n materialFilePath: string,\n options: MaterialValidationOptions = {}\n): Promise<ValidationResult> {\n const errors: string[] = [];\n const warnings: string[] = [];\n const result = { errors, warnings };\n\n const materialId = basename(materialFilePath).replace(/\\.[^/.]+$/, '');\n if (!LEARNING_MATERIAL_ID_REGEX.test(materialId)) {\n errors.push(`material ID \"${materialId}\" (file name without extension) must match ${LEARNING_MATERIAL_ID_REGEX}`);\n }\n\n let markdown: string;\n try {\n markdown = await readFile(materialFilePath, 'utf8');\n } catch {\n errors.push(`material file not found: ${materialFilePath}`);\n return result;\n }\n\n let attributes: unknown;\n let body: string;\n try {\n ({ attributes, body } = parseFrontmatter(markdown));\n } catch (error) {\n errors.push(`invalid YAML frontmatter: ${getErrorMessage(error)}`);\n return result;\n }\n\n const parsedFrontmatter = materialFrontmatterSchema.safeParse(attributes);\n if (!parsedFrontmatter.success) {\n errors.push(...formatZodIssues(parsedFrontmatter.error, 'frontmatter'));\n }\n const frontmatter = parsedFrontmatter.success ? parsedFrontmatter.data : undefined;\n\n const questionsInCodeBlocks = parseQuestionCodeBlocks(body, errors);\n const questionBlockIds = questionsInCodeBlocks.map((question) => question.id);\n const questions = [...(frontmatter?.questions ?? []), ...questionsInCodeBlocks];\n for (const question of questions) {\n validateQuestion(question, errors);\n }\n reportDuplicateIds(\n questions.map((question) => question.id),\n 'question',\n errors\n );\n // Turtle-graphics links in the body merge into the frontmatter list like problem links do,\n // and exercode rejects duplicates in the merged list; deferred until after the question blocks\n // are removed below so links inside question text don't count.\n\n // Exercode's import validation runs two checks: the body must not link the same problem,\n // question or turtle-graphics question twice (every occurrence of the lax link pattern counts),\n // and the generated reference list (frontmatter entries plus the judge's deduplicated body links)\n // must not repeat an ID. The judge replaces recognized question blocks with @[question](id) links\n // before collecting links, so links that appear only inside question text must not count, while\n // each block counts as one question link next to explicit @[question](id) links.\n const bodyWithoutQuestionBlocks = body.replaceAll(QUESTION_CODE_BLOCK_REGEX, '\\n');\n reportDuplicateIds(\n [...questionBlockIds, ...collectLinkedIds(bodyWithoutQuestionBlocks, QUESTION_LINK_REGEX)],\n 'question link',\n errors\n );\n reportDuplicateIds(collectLinkedIds(bodyWithoutQuestionBlocks, PROBLEM_ASSIGNMENT_REGEX), 'problem link', errors);\n reportDuplicateIds(\n collectLinkedIds(bodyWithoutQuestionBlocks, TURTLE_GRAPHICS_ASSIGNMENT_REGEX),\n 'turtle-graphics question link',\n errors\n );\n const linkedTurtleGraphicsQuestionIds = new Set(\n collectLinkedIds(bodyWithoutQuestionBlocks, TURTLE_GRAPHICS_QUESTION_LINK_REGEX)\n );\n reportDuplicateIds(\n [\n ...(frontmatter?.turtleGraphicsQuestions ?? []).map((question) => question.id),\n ...linkedTurtleGraphicsQuestionIds,\n ],\n 'turtleGraphicsQuestion',\n errors\n );\n // Only the links the judge collects become references, and it deduplicates them before merging.\n const problemIds = [\n ...(frontmatter?.problems ?? []).map((problem) => problem.id),\n ...new Set(collectLinkedIds(bodyWithoutQuestionBlocks, PROBLEM_LINK_REGEX)),\n ];\n reportDuplicateIds(problemIds, 'problem', errors);\n reportForeignProblemCourseIds(frontmatter?.problems ?? [], options.courseId, errors);\n const availableProblemIds =\n options.availableProblemIds ??\n (options.problemsDirectoryPath === undefined\n ? undefined\n : await collectProblemIdsFromDirectory(options.problemsDirectoryPath, errors));\n if (availableProblemIds !== undefined) {\n reportDanglingProblemReferences(problemIds, availableProblemIds, options.problemsDirectoryPath, errors);\n }\n\n reportExcessChatMarkers(body, errors);\n\n if (frontmatter) {\n validateSubmissionPeriods(\n mergeSubmissionPeriods(frontmatter, options.courseSubmissionPeriods),\n errors,\n frontmatter\n );\n }\n return result;\n}\n\nfunction collectLinkedIds(body: string, linkRegex: RegExp): string[] {\n return [...body.matchAll(linkRegex)].map((match) => match[1]).filter((id) => id !== undefined);\n}\n\n/** Applies the judge's course→material config merge (`material[field] ?? course[field]`). */\nexport function mergeSubmissionPeriods(\n own: SubmissionPeriods,\n courseDefaults: SubmissionPeriods | undefined\n): SubmissionPeriods {\n return {\n submissionOpenedAt: own.submissionOpenedAt ?? courseDefaults?.submissionOpenedAt,\n submissionSoftClosedAt: own.submissionSoftClosedAt ?? courseDefaults?.submissionSoftClosedAt,\n submissionHardClosedAt: own.submissionHardClosedAt ?? courseDefaults?.submissionHardClosedAt,\n };\n}\n\n/** exercode rejects more than one standalone chat delimiter line in material and problem bodies. */\nexport function reportExcessChatMarkers(body: string, errors: string[]): void {\n const chatMarkerCount = [...body.matchAll(STANDALONE_CHAT_MARKER_REGEX)].length;\n if (chatMarkerCount > 1) {\n errors.push(`at most one \\`${CHAT_MARKER}\\` marker is allowed, but found ${chatMarkerCount}`);\n }\n}\n\n/** The judge's resolveProblemCourseId throws when a problem reference names a different course. */\nexport function reportForeignProblemCourseIds(\n problems: readonly { id: string; courseId?: string }[],\n courseId: string | undefined,\n errors: string[]\n): void {\n if (courseId === undefined) return;\n for (const problem of problems) {\n if (problem.courseId !== undefined && problem.courseId !== courseId) {\n errors.push(`problem \"${problem.id}\": courseId must be \"${courseId}\" but is \"${problem.courseId}\"`);\n }\n }\n}\n\nfunction parseQuestionCodeBlocks(body: string, errors: string[]): MaterialQuestion[] {\n const questions: MaterialQuestion[] = [];\n const matches = [...body.matchAll(QUESTION_CODE_BLOCK_REGEX)];\n // The judge silently renders unparsed question blocks as plain code blocks, so a block the\n // strict regex misses (CRLF line endings, or no newline after the closing fence) would break\n // in production while looking fine here; flag it instead of validating a lie. Openers inside a\n // recognized block (e.g. an example fence in a question's text) are consumed with that block.\n const leftoverOpenerCount = [\n ...body.replaceAll(QUESTION_CODE_BLOCK_REGEX, '\\n').matchAll(QUESTION_CODE_BLOCK_OPENER_REGEX),\n ].length;\n if (leftoverOpenerCount > 0) {\n errors.push(\n `${leftoverOpenerCount} question code block(s) will not be recognized by the judge parser; separate consecutive question blocks with a blank line, use LF line endings, no indentation or trailing whitespace on the fence line, and end the closing fence with a newline`\n );\n }\n for (const [blockIndex, match] of matches.entries()) {\n const yamlText = match.groups?.['yaml'] ?? '';\n let rawQuestion: unknown;\n try {\n rawQuestion = parseYaml(yamlText);\n } catch (error) {\n errors.push(`question block ${blockIndex + 1}: invalid YAML: ${getErrorMessage(error)}`);\n continue;\n }\n const parsed = questionInCodeBlockSchema.safeParse(rawQuestion);\n if (parsed.success) {\n questions.push(parsed.data);\n } else {\n errors.push(...formatZodIssues(parsed.error, `question block ${blockIndex + 1}`));\n }\n }\n return questions;\n}\n\nfunction validateQuestion(question: MaterialQuestion, errors: string[]): void {\n const isSurvey = question.isSurvey === true;\n const [answerFieldName, isAnswerDefined] =\n question.type === 'select'\n ? (['answerIndex', question.answerIndex !== undefined] as const)\n : question.type === 'select_multiple'\n ? (['answerIndices', question.answerIndices !== undefined] as const)\n : (['answerPattern', question.answerPattern !== undefined] as const);\n if (isSurvey && isAnswerDefined) {\n errors.push(`question ${question.id}: \\`${answerFieldName}\\` must not be set when \\`isSurvey\\` is true`);\n }\n if (!isSurvey && !isAnswerDefined) {\n errors.push(`question ${question.id}: \\`${answerFieldName}\\` is required when \\`isSurvey\\` is not true`);\n }\n\n if (question.type === 'select' || question.type === 'select_multiple') {\n const answerIndices =\n question.type === 'select'\n ? Array.isArray(question.answerIndex)\n ? question.answerIndex\n : question.answerIndex === undefined\n ? []\n : [question.answerIndex]\n : (question.answerIndices ?? []);\n // An empty answer set is broken at runtime (select: never correct; select_multiple: an empty\n // submission grades as correct), and exercode's material editor rejects it as well.\n if (!isSurvey && isAnswerDefined && answerIndices.length === 0) {\n errors.push(`question ${question.id}: \\`${answerFieldName}\\` must contain at least one correct answer`);\n }\n for (const answerIndex of answerIndices) {\n if (!Number.isInteger(answerIndex) || answerIndex < 0 || answerIndex >= question.options.length) {\n errors.push(\n `question ${question.id}: ${answerFieldName} out of bounds: ${answerIndex}; expected 0 <= index < options length ${question.options.length}`\n );\n }\n }\n return;\n }\n\n if (isSurvey || question.answerPattern === undefined) return;\n const answerPattern = question.answerPattern.trim();\n let answerRegExp: RegExp;\n let rawAnswerRegExp: RegExp;\n try {\n answerRegExp = new RegExp(`^(?:${answerPattern})$`);\n // Compiled inside the same guard: a pattern like `a)(b` is valid only once wrapped above,\n // so an unguarded raw compile would crash the CLI instead of reporting an error.\n rawAnswerRegExp = new RegExp(question.answerPattern);\n } catch {\n errors.push(\n `question ${question.id}: \\`answerPattern\\` is not a valid regular expression: ${question.answerPattern}`\n );\n return;\n }\n // Mirrors the judge heuristic: a pattern that doesn't match itself likely uses RegExp syntax,\n // so a modelAnswer is required to prove that some concrete answer is accepted.\n // Like the judge, an empty modelAnswer counts as missing.\n // The judge runs this heuristic on the untrimmed pattern and trims only for the anchored match.\n if (!question.modelAnswer && !rawAnswerRegExp.test(question.answerPattern)) {\n errors.push(`question ${question.id}: \\`answerPattern\\` seems a RegExp but \\`modelAnswer\\` is missing`);\n }\n if (question.modelAnswer && !answerRegExp.test(question.modelAnswer.trim())) {\n errors.push(`question ${question.id}: \\`modelAnswer\\` doesn't match \\`answerPattern\\``);\n }\n}\n\n/**\n * Reports inverted submission periods; shared by material, course.yaml, and contest validation.\n * When `ownPeriods` is given (the merged-values case), pairs whose both values are inherited from\n * the course are skipped: they are the course's mistake and are already reported against\n * course.yaml, so repeating them per material would send agents to files with nothing to fix.\n */\nexport function validateSubmissionPeriods(\n periods: SubmissionPeriods,\n errors: string[],\n ownPeriods: SubmissionPeriods = periods\n): void {\n const pairs = [\n ['submissionOpenedAt', 'submissionSoftClosedAt'],\n ['submissionSoftClosedAt', 'submissionHardClosedAt'],\n ['submissionOpenedAt', 'submissionHardClosedAt'],\n ] as const satisfies readonly (readonly [keyof SubmissionPeriods, keyof SubmissionPeriods])[];\n for (const [earlierName, laterName] of pairs) {\n const earlierValue = periods[earlierName];\n const laterValue = periods[laterName];\n if (earlierValue === undefined || laterValue === undefined) continue;\n if (ownPeriods[earlierName] === undefined && ownPeriods[laterName] === undefined) continue;\n if (new Date(laterValue).getTime() < new Date(earlierValue).getTime()) {\n errors.push(`${earlierName} (${earlierValue}) must be <= ${laterName} (${laterValue})`);\n }\n }\n}\n"],"mappings":"8PAmBA,MAAMkB,EAA4B,gFAG5BC,EAAmC,8DACnCC,EAAqB,sCACrBC,EAAsC,uDAGtCC,EAA2B,wCAC3BC,EAAsB,iCACtBC,EAAmC,yDAGnCC,EAA+B,2CAoBrC,eAAsBC,EACpB,EACA,EAAqC,CAAC,EACX,CAC3B,IAAMC,EAAmB,CAAC,EAEpBC,EAAS,CAAE,SAAQ,SAAA,CAAO,CAAE,EAE5BC,GAAA,EAAa7B,EAAAA,SAAAA,CAAS8B,CAAgB,CAAC,CAAC,QAAQ,YAAa,EAAE,EAChE7B,EAAAA,2BAA2B,KAAK4B,CAAU,GAC7CF,EAAO,KAAK,gBAAgBE,EAAW,6CAA6C5B,EAAAA,4BAA4B,EAGlH,IAAI8B,EACJ,GAAI,CACF,EAAW,MAAA,EAAM7B,EAAAA,SAAAA,CAAS4B,EAAkB,MAAM,CACpD,MAAQ,CAEN,OADAH,EAAO,KAAK,4BAA4BG,GAAkB,EACnDF,CACT,CAEA,IAAII,EACAC,EACJ,GAAI,EACD,sBAAuB9B,EAAAA,iBAAiB4B,CAAQ,EACnD,OAASG,EAAO,CAEd,OADAP,EAAO,KAAK,8BAAA,EAA6BvB,EAAAA,gBAAAA,CAAgB8B,CAAK,GAAG,EAC1DN,CACT,CAEA,IAAMO,EAAoB9B,EAAAA,0BAA0B,UAAU2B,CAAU,EACnEG,EAAkB,SACrBR,EAAO,KAAK,GAAGrB,EAAAA,gBAAgB6B,EAAkB,MAAO,aAAa,CAAC,EAExE,IAAMC,EAAcD,EAAkB,QAAUA,EAAkB,KAAO,IAAA,GAEnEE,EAA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