@exercode/problem-utils 2.4.3 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +23 -0
  2. package/dist/cli/checkAllProblems.cjs +1 -1
  3. package/dist/cli/checkAllProblems.cjs.map +1 -1
  4. package/dist/cli/checkAllProblems.js +1 -1
  5. package/dist/cli/checkAllProblems.js.map +1 -1
  6. package/dist/cli/exercodeProblem.cjs +8 -2
  7. package/dist/cli/exercodeProblem.cjs.map +1 -1
  8. package/dist/cli/exercodeProblem.js +8 -2
  9. package/dist/cli/exercodeProblem.js.map +1 -1
  10. package/dist/cli/validateLearningMaterial.cjs +2 -0
  11. package/dist/cli/validateLearningMaterial.cjs.map +1 -0
  12. package/dist/cli/validateLearningMaterial.d.ts +7 -0
  13. package/dist/cli/validateLearningMaterial.js +2 -0
  14. package/dist/cli/validateLearningMaterial.js.map +1 -0
  15. package/dist/helpers/checkProblemDirIsolation.cjs +1 -1
  16. package/dist/helpers/checkProblemDirIsolation.js +1 -1
  17. package/dist/helpers/cleanWorkingDirectory.cjs +1 -1
  18. package/dist/helpers/cleanWorkingDirectory.cjs.map +1 -1
  19. package/dist/helpers/cleanWorkingDirectory.d.ts +2 -6
  20. package/dist/helpers/cleanWorkingDirectory.js +1 -1
  21. package/dist/helpers/cleanWorkingDirectory.js.map +1 -1
  22. package/dist/helpers/compareExpectedOutputFiles.cjs +1 -1
  23. package/dist/helpers/compareExpectedOutputFiles.cjs.map +1 -1
  24. package/dist/helpers/compareExpectedOutputFiles.js +1 -1
  25. package/dist/helpers/compareExpectedOutputFiles.js.map +1 -1
  26. package/dist/helpers/copyTestCaseFileInput.cjs +1 -1
  27. package/dist/helpers/copyTestCaseFileInput.cjs.map +1 -1
  28. package/dist/helpers/copyTestCaseFileInput.js +1 -1
  29. package/dist/helpers/copyTestCaseFileInput.js.map +1 -1
  30. package/dist/helpers/judgeByStaticAnalysis.cjs +3 -3
  31. package/dist/helpers/judgeByStaticAnalysis.js +3 -3
  32. package/dist/helpers/readOutputFiles.cjs +1 -1
  33. package/dist/helpers/readOutputFiles.cjs.map +1 -1
  34. package/dist/helpers/readOutputFiles.d.ts +0 -9
  35. package/dist/helpers/readOutputFiles.js +1 -1
  36. package/dist/helpers/readOutputFiles.js.map +1 -1
  37. package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs +1 -1
  38. package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs.map +1 -1
  39. package/dist/helpers/runCommandInTemporaryPackageManagerProject.d.ts +0 -3
  40. package/dist/helpers/runCommandInTemporaryPackageManagerProject.js +1 -1
  41. package/dist/helpers/runCommandInTemporaryPackageManagerProject.js.map +1 -1
  42. package/dist/helpers/spawnSyncWithTimeout.cjs +1 -1
  43. package/dist/helpers/spawnSyncWithTimeout.cjs.map +1 -1
  44. package/dist/helpers/spawnSyncWithTimeout.d.ts +0 -7
  45. package/dist/helpers/spawnSyncWithTimeout.js +1 -1
  46. package/dist/helpers/spawnSyncWithTimeout.js.map +1 -1
  47. package/dist/helpers/startHttpServer.cjs +1 -1
  48. package/dist/helpers/startHttpServer.cjs.map +1 -1
  49. package/dist/helpers/startHttpServer.js +1 -1
  50. package/dist/helpers/startHttpServer.js.map +1 -1
  51. package/dist/helpers/stdioJudgeRules.cjs +2 -0
  52. package/dist/helpers/stdioJudgeRules.cjs.map +1 -0
  53. package/dist/helpers/stdioJudgeRules.d.ts +4 -0
  54. package/dist/helpers/stdioJudgeRules.js +2 -0
  55. package/dist/helpers/stdioJudgeRules.js.map +1 -0
  56. package/dist/index.cjs +1 -1
  57. package/dist/index.d.ts +5 -2
  58. package/dist/index.js +1 -1
  59. package/dist/learningMaterial/frontmatter.cjs +2 -0
  60. package/dist/learningMaterial/frontmatter.cjs.map +1 -0
  61. package/dist/learningMaterial/frontmatter.d.ts +8 -0
  62. package/dist/learningMaterial/frontmatter.js +2 -0
  63. package/dist/learningMaterial/frontmatter.js.map +1 -0
  64. package/dist/learningMaterial/fsHelpers.cjs +2 -0
  65. package/dist/learningMaterial/fsHelpers.cjs.map +1 -0
  66. package/dist/learningMaterial/fsHelpers.d.ts +30 -0
  67. package/dist/learningMaterial/fsHelpers.js +2 -0
  68. package/dist/learningMaterial/fsHelpers.js.map +1 -0
  69. package/dist/learningMaterial/schemas.cjs +2 -0
  70. package/dist/learningMaterial/schemas.cjs.map +1 -0
  71. package/dist/learningMaterial/schemas.d.ts +241 -0
  72. package/dist/learningMaterial/schemas.js +2 -0
  73. package/dist/learningMaterial/schemas.js.map +1 -0
  74. package/dist/learningMaterial/validateContest.cjs +2 -0
  75. package/dist/learningMaterial/validateContest.cjs.map +1 -0
  76. package/dist/learningMaterial/validateContest.d.ts +16 -0
  77. package/dist/learningMaterial/validateContest.js +2 -0
  78. package/dist/learningMaterial/validateContest.js.map +1 -0
  79. package/dist/learningMaterial/validateCourse.cjs +2 -0
  80. package/dist/learningMaterial/validateCourse.cjs.map +1 -0
  81. package/dist/learningMaterial/validateCourse.d.ts +11 -0
  82. package/dist/learningMaterial/validateCourse.js +2 -0
  83. package/dist/learningMaterial/validateCourse.js.map +1 -0
  84. package/dist/learningMaterial/validateMaterial.cjs +4 -0
  85. package/dist/learningMaterial/validateMaterial.cjs.map +1 -0
  86. package/dist/learningMaterial/validateMaterial.d.ts +34 -0
  87. package/dist/learningMaterial/validateMaterial.js +4 -0
  88. package/dist/learningMaterial/validateMaterial.js.map +1 -0
  89. package/dist/learningMaterial/validateProblem.cjs +2 -0
  90. package/dist/learningMaterial/validateProblem.cjs.map +1 -0
  91. package/dist/learningMaterial/validateProblem.d.ts +6 -0
  92. package/dist/learningMaterial/validateProblem.js +2 -0
  93. package/dist/learningMaterial/validateProblem.js.map +1 -0
  94. package/dist/learningMaterial/validationResult.cjs +3 -0
  95. package/dist/learningMaterial/validationResult.cjs.map +1 -0
  96. package/dist/learningMaterial/validationResult.d.ts +9 -0
  97. package/dist/learningMaterial/validationResult.js +3 -0
  98. package/dist/learningMaterial/validationResult.js.map +1 -0
  99. package/dist/presets/command.cjs +1 -1
  100. package/dist/presets/command.cjs.map +1 -1
  101. package/dist/presets/command.d.ts +0 -16
  102. package/dist/presets/command.js +1 -1
  103. package/dist/presets/command.js.map +1 -1
  104. package/dist/presets/evaluation.cjs +4 -4
  105. package/dist/presets/evaluation.cjs.map +1 -1
  106. package/dist/presets/evaluation.js +4 -4
  107. package/dist/presets/evaluation.js.map +1 -1
  108. package/dist/presets/guiCommand.cjs +3 -3
  109. package/dist/presets/guiCommand.cjs.map +1 -1
  110. package/dist/presets/guiCommand.d.ts +0 -24
  111. package/dist/presets/guiCommand.js +3 -3
  112. package/dist/presets/guiCommand.js.map +1 -1
  113. package/dist/presets/stdio.cjs +1 -1
  114. package/dist/presets/stdio.cjs.map +1 -1
  115. package/dist/presets/stdio.js +1 -1
  116. package/dist/presets/stdio.js.map +1 -1
  117. package/dist/types/language.cjs +2 -2
  118. package/dist/types/language.cjs.map +1 -1
  119. package/dist/types/language.js +2 -2
  120. package/dist/types/language.js.map +1 -1
  121. package/package.json +3 -2
  122. package/dist/helpers/runCustomRunner.cjs +0 -2
  123. package/dist/helpers/runCustomRunner.cjs.map +0 -1
  124. package/dist/helpers/runCustomRunner.d.ts +0 -8
  125. package/dist/helpers/runCustomRunner.js +0 -2
  126. package/dist/helpers/runCustomRunner.js.map +0 -1
  127. package/dist/helpers/safeFs.cjs +0 -2
  128. package/dist/helpers/safeFs.cjs.map +0 -1
  129. package/dist/helpers/safeFs.d.ts +0 -29
  130. package/dist/helpers/safeFs.js +0 -2
  131. package/dist/helpers/safeFs.js.map +0 -1
  132. package/dist/helpers/sandboxUser.cjs +0 -3
  133. package/dist/helpers/sandboxUser.cjs.map +0 -1
  134. package/dist/helpers/sandboxUser.d.ts +0 -146
  135. package/dist/helpers/sandboxUser.js +0 -3
  136. package/dist/helpers/sandboxUser.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"compareExpectedOutputFiles.cjs","names":["fs","path","encodeFileForTestCaseResult","compareStdoutAsSpaceSeparatedTokens","isSafeSubmissionOutputPath"],"sources":["../../src/helpers/compareExpectedOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { compareStdoutAsSpaceSeparatedTokens } from './compareStdoutAsSpaceSeparatedTokens.js';\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\nimport { isSafeSubmissionOutputPath } from './readOutputFiles.js';\n\ntype OutputFile = NonNullable<TestCaseResult['outputFiles']>[number];\n\n// A submission controls the received files, so bound what the trusted harness reads and reports.\nexport const MAX_COMPARED_FILE_BYTES = 8 * 1024 * 1024;\nexport const MAX_REPORTED_FILE_BYTES = 1024 * 1024;\n\nexport interface ExpectedOutputFilesComparison {\n /** Whether every file under the expected directory has a matching file in the working directory. */\n matches: boolean;\n /** Relative paths (from the working directory) of the files that are missing or different. */\n mismatchedPaths: string[];\n /**\n * `<name>_expected.<ext>` / `<name>_received.<ext>` pairs for each mismatched file, in the\n * format Exercode renders side by side. A received file that is missing, unreadable, not a\n * regular file or larger than `MAX_COMPARED_FILE_BYTES` yields only the expected entry, and a\n * file larger than `MAX_REPORTED_FILE_BYTES` is left out of the pair. Exercode decides per test case whether a learner may see these files.\n */\n outputFiles: OutputFile[];\n}\n\n/**\n * Compare the files under a test case's `.fout` directory with the files the submission wrote to\n * its working directory. Text files are compared like stdout (space-separated tokens with a\n * numeric tolerance); binary files must match byte for byte.\n */\nexport async function compareExpectedOutputFiles(\n cwd: string,\n fileOutputPath: string\n): Promise<ExpectedOutputFilesComparison> {\n const mismatchedPaths: string[] = [];\n const outputFiles: OutputFile[] = [];\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n const expectedFiles = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => ({\n absolutePath: path.join(dirent.parentPath, dirent.name),\n // POSIX separators: `requiredOutputFilePaths` and the result format use them on every platform.\n relativePath: path.posix.join(...path.relative(fileOutputPath, dirent.parentPath).split(path.sep), dirent.name),\n }))\n .toSorted((a, b) => (a.relativePath < b.relativePath ? -1 : a.relativePath > b.relativePath ? 1 : 0));\n for (const { absolutePath, relativePath } of expectedFiles) {\n // A larger expectation could never be matched by a received file, so it is an authoring error.\n const expectedStats = await fs.promises.stat(absolutePath);\n if (expectedStats.size > MAX_COMPARED_FILE_BYTES) {\n throw new Error(`expected output file ${relativePath} exceeds ${MAX_COMPARED_FILE_BYTES} bytes`);\n }\n const expected = await fs.promises.readFile(absolutePath);\n const received = await readReceivedFile(cwd, path.join(cwd, relativePath));\n if (received && fileContentsMatch(expected, received)) continue;\n\n mismatchedPaths.push(relativePath);\n // A file too large to ship in a result line is left out of the pair rather than truncated.\n if (expected.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'expected'), expected));\n }\n if (received && received.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'received'), received));\n }\n }\n return { matches: mismatchedPaths.length === 0, mismatchedPaths, outputFiles };\n}\n\n/**\n * The default verdict of the presets: `.out` decides stdout and `.fout/` decides output files, both\n * checked so a result carries every mismatch; either expectation may be absent. Returns whether the\n * run matched and the output files to report (the plain copies of mismatched required output files\n * replaced by their comparison pairs).\n */\nexport async function judgeAgainstExpectations(context: {\n stdout: string;\n expectedStdout: string | undefined;\n fileOutputPath: string | undefined;\n cwd: string;\n outputFiles: readonly OutputFile[];\n}): Promise<{ matches: boolean; outputFiles: OutputFile[] }> {\n const { stdout, expectedStdout, fileOutputPath, cwd } = context;\n let outputFiles = [...context.outputFiles];\n let matches = expectedStdout === undefined || compareStdoutAsSpaceSeparatedTokens(stdout, expectedStdout);\n if (fileOutputPath !== undefined) {\n const comparison = await compareExpectedOutputFiles(cwd, fileOutputPath);\n if (!comparison.matches) {\n matches = false;\n outputFiles = mergeComparisonOutputFiles(outputFiles, comparison);\n }\n }\n return { matches, outputFiles };\n}\n\n/**\n * Replace the plain copies of mismatched required output files with the comparison pairs, so a\n * result shows `<name>_expected.<ext>` / `<name>_received.<ext>` instead of a lone `<name>.<ext>`.\n */\nexport function mergeComparisonOutputFiles(\n outputFiles: readonly OutputFile[],\n comparison: ExpectedOutputFilesComparison\n): OutputFile[] {\n const comparisonPaths = new Set(comparison.outputFiles.map((file) => file.path));\n // The plain copy gives way to its `_received` entry; a mismatch too large for a pair keeps the\n // plain copy, and a kept file literally named like a pair entry would make the path ambiguous.\n const replacedPaths = new Set(\n comparison.mismatchedPaths.filter((filePath) => comparisonPaths.has(toComparisonPath(filePath, 'received')))\n );\n return [\n ...outputFiles.filter((file) => !replacedPaths.has(file.path) && !comparisonPaths.has(file.path)),\n ...comparison.outputFiles,\n ];\n}\n\n/** `c.txt` → `c_expected.txt`; `out/c.txt` → `out/c_expected.txt`. */\nfunction toComparisonPath(filePath: string, role: 'expected' | 'received'): string {\n const { dir, name, ext } = path.posix.parse(filePath);\n return path.posix.join(dir, `${name}_${role}${ext}`);\n}\n\n// A submission controls this path, so anything that is not a plain, readable file within the size\n// limit (a directory, a FIFO that would block, an unreadable or huge file) counts as \"not produced\".\nasync function readReceivedFile(cwd: string, receivedPath: string): Promise<Buffer | undefined> {\n // A submission-planted symlink to the expected file itself would otherwise compare equal.\n if (!(await isSafeSubmissionOutputPath(cwd, receivedPath))) return undefined;\n try {\n const stats = await fs.promises.stat(receivedPath);\n if (!stats.isFile() || stats.size > MAX_COMPARED_FILE_BYTES) return undefined;\n return await fs.promises.readFile(receivedPath);\n } catch {\n return undefined;\n }\n}\n\nfunction fileContentsMatch(expected: Buffer, received: Buffer): boolean {\n if (!isTextFile(expected)) return received.equals(expected);\n if (!isTextFile(received)) return false;\n return compareStdoutAsSpaceSeparatedTokens(received.toString('utf8'), expected.toString('utf8'));\n}\n\nconst utf8Decoder = new TextDecoder('utf-8', { fatal: true });\n\n// Valid UTF-8 without NUL bytes: a binary format that happens to decode (e.g. a PNG chunk) almost\n// always contains NUL, while text files containing U+FFFD are still treated as text.\nfunction isTextFile(data: Buffer): boolean {\n if (data.includes(0)) return false;\n try {\n utf8Decoder.decode(data);\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":"yRAYA,MAAa,EAA0B,QAsBvC,eAAsB,EACpB,EACA,EACwC,CACxC,IAAM,EAA4B,CAAC,EAC7B,EAA4B,CAAC,EAE7B,GAAgB,MADAA,EAAAA,QAAG,SAAS,QAAQ,EAAgB,CAAE,cAAe,GAAM,UAAW,EAAK,CAAC,EAAA,CAE/F,OAAQ,GAAW,EAAO,OAAO,CAAC,CAAC,CACnC,IAAK,IAAY,CAChB,aAAcC,EAAAA,QAAK,KAAK,EAAO,WAAY,EAAO,IAAI,EAEtD,aAAcA,EAAAA,QAAK,MAAM,KAAK,GAAGA,EAAAA,QAAK,SAAS,EAAgB,EAAO,UAAU,CAAC,CAAC,MAAMA,EAAAA,QAAK,GAAG,EAAG,EAAO,IAAI,CAChH,EAAE,CAAC,CACF,UAAU,EAAG,IAAO,EAAE,aAAe,EAAE,aAAe,GAAK,IAAE,aAAe,EAAE,aAAqB,EACtG,IAAK,GAAM,CAAE,eAAc,kBAAkB,EAAe,CAG1D,IAAI,MADwBD,EAAAA,QAAG,SAAS,KAAK,CAAY,EAAA,CACvC,KAAA,QAChB,MAAU,MAAM,wBAAwB,EAAa,WAAW,EAAwB,OAAO,EAEjG,IAAM,EAAW,MAAMA,EAAAA,QAAG,SAAS,SAAS,CAAY,EAClD,EAAW,MAAM,EAAiB,EAAKC,EAAAA,QAAK,KAAK,EAAK,CAAY,CAAC,EACrE,GAAY,EAAkB,EAAU,CAAQ,IAEpD,EAAgB,KAAK,CAAY,EAE7B,EAAS,QAAA,SACX,EAAY,KAAKC,EAAAA,4BAA4B,EAAiB,EAAc,UAAU,EAAG,CAAQ,CAAC,EAEhG,GAAY,EAAS,QAAA,SACvB,EAAY,KAAKA,EAAAA,4BAA4B,E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ChD,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAkB,EAAkB,EAA2B,CAGtE,OAFK,EAAW,CAAQ,EACnB,EAAW,CAAQ,EACjBG,EAAAA,oCAAoC,EAAS,SAAS,MAAM,EAAG,EAAS,SAAS,MAAM,CAAC,EAD7D,GADA,EAAS,OAAO,CAAQ,CAG5D,CAEA,MAAM,EAAc,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,EAI5D,SAAS,EAAW,EAAuB,CACzC,GAAI,EAAK,SAAS,CAAC,EAAG,MAAO,GAC7B,GAAI,CAEF,OADA,EAAY,OAAO,CAAI,EAChB,EACT,MAAQ,CACN,MAAO,EACT,CACF"}
1
+ {"version":3,"file":"compareExpectedOutputFiles.cjs","names":["fs","path","encodeFileForTestCaseResult","compareStdoutAsSpaceSeparatedTokens"],"sources":["../../src/helpers/compareExpectedOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { compareStdoutAsSpaceSeparatedTokens } from './compareStdoutAsSpaceSeparatedTokens.js';\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\n\ntype OutputFile = NonNullable<TestCaseResult['outputFiles']>[number];\n\n// Bound what the harness reads and reports.\nexport const MAX_COMPARED_FILE_BYTES = 8 * 1024 * 1024;\nexport const MAX_REPORTED_FILE_BYTES = 1024 * 1024;\n\nexport interface ExpectedOutputFilesComparison {\n /** Whether every file under the expected directory has a matching file in the working directory. */\n matches: boolean;\n /** Relative paths (from the working directory) of the files that are missing or different. */\n mismatchedPaths: string[];\n /**\n * `<name>_expected.<ext>` / `<name>_received.<ext>` pairs for each mismatched file, in the\n * format Exercode renders side by side. A received file that is missing, unreadable, not a\n * regular file or larger than `MAX_COMPARED_FILE_BYTES` yields only the expected entry, and a\n * file larger than `MAX_REPORTED_FILE_BYTES` is left out of the pair. Exercode decides per test case whether a learner may see these files.\n */\n outputFiles: OutputFile[];\n}\n\n/**\n * Compare the files under a test case's `.fout` directory with the files the submission wrote to\n * its working directory. Text files are compared like stdout (space-separated tokens with a\n * numeric tolerance); binary files must match byte for byte.\n */\nexport async function compareExpectedOutputFiles(\n cwd: string,\n fileOutputPath: string\n): Promise<ExpectedOutputFilesComparison> {\n const mismatchedPaths: string[] = [];\n const outputFiles: OutputFile[] = [];\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n const expectedFiles = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => ({\n absolutePath: path.join(dirent.parentPath, dirent.name),\n // POSIX separators: `requiredOutputFilePaths` and the result format use them on every platform.\n relativePath: path.posix.join(...path.relative(fileOutputPath, dirent.parentPath).split(path.sep), dirent.name),\n }))\n .toSorted((a, b) => (a.relativePath < b.relativePath ? -1 : a.relativePath > b.relativePath ? 1 : 0));\n for (const { absolutePath, relativePath } of expectedFiles) {\n // A larger expectation could never be matched by a received file, so it is an authoring error.\n const expectedStats = await fs.promises.stat(absolutePath);\n if (expectedStats.size > MAX_COMPARED_FILE_BYTES) {\n throw new Error(`expected output file ${relativePath} exceeds ${MAX_COMPARED_FILE_BYTES} bytes`);\n }\n const expected = await fs.promises.readFile(absolutePath);\n const received = await readReceivedFile(path.join(cwd, relativePath));\n if (received && fileContentsMatch(expected, received)) continue;\n\n mismatchedPaths.push(relativePath);\n // A file too large to ship in a result line is left out of the pair rather than truncated.\n if (expected.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'expected'), expected));\n }\n if (received && received.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'received'), received));\n }\n }\n return { matches: mismatchedPaths.length === 0, mismatchedPaths, outputFiles };\n}\n\n/**\n * The default verdict of the presets: `.out` decides stdout and `.fout/` decides output files, both\n * checked so a result carries every mismatch; either expectation may be absent. Returns whether the\n * run matched and the output files to report (the plain copies of mismatched required output files\n * replaced by their comparison pairs).\n */\nexport async function judgeAgainstExpectations(context: {\n stdout: string;\n expectedStdout: string | undefined;\n fileOutputPath: string | undefined;\n cwd: string;\n outputFiles: readonly OutputFile[];\n}): Promise<{ matches: boolean; outputFiles: OutputFile[] }> {\n const { stdout, expectedStdout, fileOutputPath, cwd } = context;\n let outputFiles = [...context.outputFiles];\n let matches = expectedStdout === undefined || compareStdoutAsSpaceSeparatedTokens(stdout, expectedStdout);\n if (fileOutputPath !== undefined) {\n const comparison = await compareExpectedOutputFiles(cwd, fileOutputPath);\n if (!comparison.matches) {\n matches = false;\n outputFiles = mergeComparisonOutputFiles(outputFiles, comparison);\n }\n }\n return { matches, outputFiles };\n}\n\n/**\n * Replace the plain copies of mismatched required output files with the comparison pairs, so a\n * result shows `<name>_expected.<ext>` / `<name>_received.<ext>` instead of a lone `<name>.<ext>`.\n */\nexport function mergeComparisonOutputFiles(\n outputFiles: readonly OutputFile[],\n comparison: ExpectedOutputFilesComparison\n): OutputFile[] {\n const comparisonPaths = new Set(comparison.outputFiles.map((file) => file.path));\n // The plain copy gives way to its `_received` entry; a mismatch too large for a pair keeps the\n // plain copy, and a kept file literally named like a pair entry would make the path ambiguous.\n const replacedPaths = new Set(\n comparison.mismatchedPaths.filter((filePath) => comparisonPaths.has(toComparisonPath(filePath, 'received')))\n );\n return [\n ...outputFiles.filter((file) => !replacedPaths.has(file.path) && !comparisonPaths.has(file.path)),\n ...comparison.outputFiles,\n ];\n}\n\n/** `c.txt` → `c_expected.txt`; `out/c.txt` → `out/c_expected.txt`. */\nfunction toComparisonPath(filePath: string, role: 'expected' | 'received'): string {\n const { dir, name, ext } = path.posix.parse(filePath);\n return path.posix.join(dir, `${name}_${role}${ext}`);\n}\n\n// Anything that is not a plain, readable file within the size limit (a directory, a FIFO that would\n// block, an unreadable or huge file) counts as \"not produced\".\nasync function readReceivedFile(receivedPath: string): Promise<Buffer | undefined> {\n try {\n const stats = await fs.promises.stat(receivedPath);\n if (!stats.isFile() || stats.size > MAX_COMPARED_FILE_BYTES) return undefined;\n return await fs.promises.readFile(receivedPath);\n } catch {\n return undefined;\n }\n}\n\nfunction fileContentsMatch(expected: Buffer, received: Buffer): boolean {\n if (!isTextFile(expected)) return received.equals(expected);\n if (!isTextFile(received)) return false;\n return compareStdoutAsSpaceSeparatedTokens(received.toString('utf8'), expected.toString('utf8'));\n}\n\nconst utf8Decoder = new TextDecoder('utf-8', { fatal: true });\n\n// Valid UTF-8 without NUL bytes: a binary format that happens to decode (e.g. a PNG chunk) almost\n// always contains NUL, while text files containing U+FFFD are still treated as text.\nfunction isTextFile(data: Buffer): boolean {\n if (data.includes(0)) return false;\n try {\n utf8Decoder.decode(data);\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":"sPAWA,MAAa,EAA0B,QAsBvC,eAAsB,EACpB,EACA,EACwC,CACxC,IAAM,EAA4B,CAAC,EAC7B,EAA4B,CAAC,EAE7B,GAAgB,MADAA,EAAAA,QAAG,SAAS,QAAQ,EAAgB,CAAE,cAAe,GAAM,UAAW,EAAK,CAAC,EAAA,CAE/F,OAAQ,GAAW,EAAO,OAAO,CAAC,CAAC,CACnC,IAAK,IAAY,CAChB,aAAcC,EAAAA,QAAK,KAAK,EAAO,WAAY,EAAO,IAAI,EAEtD,aAAcA,EAAAA,QAAK,MAAM,KAAK,GAAGA,EAAAA,QAAK,SAAS,EAAgB,EAAO,UAAU,CAAC,CAAC,MAAMA,EAAAA,QAAK,GAAG,EAAG,EAAO,IAAI,CAChH,EAAE,CAAC,CACF,UAAU,EAAG,IAAO,EAAE,aAAe,EAAE,aAAe,GAAK,IAAE,aAAe,EAAE,aAAqB,EACtG,IAAK,GAAM,CAAE,eAAc,kBAAkB,EAAe,CAG1D,IAAI,MADwBD,EAAAA,QAAG,SAAS,KAAK,CAAY,EAAA,CACvC,KAAA,QAChB,MAAU,MAAM,wBAAwB,EAAa,WAAW,EAAwB,OAAO,EAEjG,IAAM,EAAW,MAAMA,EAAAA,QAAG,SAAS,S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AAK,GAAG,EAAK,GAAG,IAAO,GAAK,CACrD,CAIA,eAAe,EAAiB,EAAmD,CACjF,GAAI,CACF,IAAM,EAAQ,MAAMD,EAAAA,QAAG,SAAS,KAAK,CAAY,EAEjD,MADI,CAAC,EAAM,OAAO,GAAK,EAAM,KAAA,QAAgC,OACtD,MAAMA,EAAAA,QAAG,SAAS,SAAS,CAAY,CAChD,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAkB,EAAkB,EAA2B,CAGtE,OAFK,EAAW,CAAQ,EACnB,EAAW,CAAQ,EACjBG,EAAAA,oCAAoC,EAAS,SAAS,MAAM,EAAG,EAAS,SAAS,MAAM,CAAC,EAD7D,GADA,EAAS,OAAO,CAAQ,CAG5D,CAEA,MAAM,EAAc,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,EAI5D,SAAS,EAAW,EAAuB,CACzC,GAAI,EAAK,SAAS,CAAC,EAAG,MAAO,GAC7B,GAAI,CAEF,OADA,EAAY,OAAO,CAAI,EAChB,EACT,MAAQ,CACN,MAAO,EACT,CACF"}
@@ -1,2 +1,2 @@
1
- import{compareStdoutAsSpaceSeparatedTokens as e}from"./compareStdoutAsSpaceSeparatedTokens.js";import{encodeFileForTestCaseResult as t}from"./printTestCaseResult.js";import{isSafeSubmissionOutputPath as n}from"./readOutputFiles.js";import r from"node:fs";import i from"node:path";const a=8388608,o=1048576;async function s(e,n){let o=[],s=[],c=(await r.promises.readdir(n,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>({absolutePath:i.join(e.parentPath,e.name),relativePath:i.posix.join(...i.relative(n,e.parentPath).split(i.sep),e.name)})).toSorted((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath));for(let{absolutePath:n,relativePath:l}of c){if((await r.promises.stat(n)).size>8388608)throw Error(`expected output file ${l} exceeds ${a} bytes`);let c=await r.promises.readFile(n),p=await d(e,i.join(e,l));p&&f(c,p)||(o.push(l),c.length<=1048576&&s.push(t(u(l,`expected`),c)),p&&p.length<=1048576&&s.push(t(u(l,`received`),p)))}return{matches:o.length===0,mismatchedPaths:o,outputFiles:s}}async function c(t){let{stdout:n,expectedStdout:r,fileOutputPath:i,cwd:a}=t,o=[...t.outputFiles],c=r===void 0||e(n,r);if(i!==void 0){let e=await s(a,i);e.matches||(c=!1,o=l(o,e))}return{matches:c,outputFiles:o}}function l(e,t){let n=new Set(t.outputFiles.map(e=>e.path)),r=new Set(t.mismatchedPaths.filter(e=>n.has(u(e,`received`))));return[...e.filter(e=>!r.has(e.path)&&!n.has(e.path)),...t.outputFiles]}function u(e,t){let{dir:n,name:r,ext:a}=i.posix.parse(e);return i.posix.join(n,`${r}_${t}${a}`)}async function d(e,t){if(await n(e,t))try{let e=await r.promises.stat(t);return!e.isFile()||e.size>8388608?void 0:await r.promises.readFile(t)}catch{return}}function f(t,n){return m(t)?m(n)?e(n.toString(`utf8`),t.toString(`utf8`)):!1:n.equals(t)}const p=new TextDecoder(`utf-8`,{fatal:!0});function m(e){if(e.includes(0))return!1;try{return p.decode(e),!0}catch{return!1}}export{a as MAX_COMPARED_FILE_BYTES,o as MAX_REPORTED_FILE_BYTES,s as compareExpectedOutputFiles,c as judgeAgainstExpectations,l as mergeComparisonOutputFiles};
1
+ import{compareStdoutAsSpaceSeparatedTokens as e}from"./compareStdoutAsSpaceSeparatedTokens.js";import{encodeFileForTestCaseResult as t}from"./printTestCaseResult.js";import n from"node:fs";import r from"node:path";const i=8388608,a=1048576;async function o(e,a){let o=[],s=[],c=(await n.promises.readdir(a,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>({absolutePath:r.join(e.parentPath,e.name),relativePath:r.posix.join(...r.relative(a,e.parentPath).split(r.sep),e.name)})).toSorted((e,t)=>e.relativePath<t.relativePath?-1:+(e.relativePath>t.relativePath));for(let{absolutePath:a,relativePath:f}of c){if((await n.promises.stat(a)).size>8388608)throw Error(`expected output file ${f} exceeds ${i} bytes`);let c=await n.promises.readFile(a),p=await u(r.join(e,f));p&&d(c,p)||(o.push(f),c.length<=1048576&&s.push(t(l(f,`expected`),c)),p&&p.length<=1048576&&s.push(t(l(f,`received`),p)))}return{matches:o.length===0,mismatchedPaths:o,outputFiles:s}}async function s(t){let{stdout:n,expectedStdout:r,fileOutputPath:i,cwd:a}=t,s=[...t.outputFiles],l=r===void 0||e(n,r);if(i!==void 0){let e=await o(a,i);e.matches||(l=!1,s=c(s,e))}return{matches:l,outputFiles:s}}function c(e,t){let n=new Set(t.outputFiles.map(e=>e.path)),r=new Set(t.mismatchedPaths.filter(e=>n.has(l(e,`received`))));return[...e.filter(e=>!r.has(e.path)&&!n.has(e.path)),...t.outputFiles]}function l(e,t){let{dir:n,name:i,ext:a}=r.posix.parse(e);return r.posix.join(n,`${i}_${t}${a}`)}async function u(e){try{let t=await n.promises.stat(e);return!t.isFile()||t.size>8388608?void 0:await n.promises.readFile(e)}catch{return}}function d(t,n){return p(t)?p(n)?e(n.toString(`utf8`),t.toString(`utf8`)):!1:n.equals(t)}const f=new TextDecoder(`utf-8`,{fatal:!0});function p(e){if(e.includes(0))return!1;try{return f.decode(e),!0}catch{return!1}}export{i as MAX_COMPARED_FILE_BYTES,a as MAX_REPORTED_FILE_BYTES,o as compareExpectedOutputFiles,s as judgeAgainstExpectations,c as mergeComparisonOutputFiles};
2
2
  //# sourceMappingURL=compareExpectedOutputFiles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compareExpectedOutputFiles.js","names":[],"sources":["../../src/helpers/compareExpectedOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { compareStdoutAsSpaceSeparatedTokens } from './compareStdoutAsSpaceSeparatedTokens.js';\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\nimport { isSafeSubmissionOutputPath } from './readOutputFiles.js';\n\ntype OutputFile = NonNullable<TestCaseResult['outputFiles']>[number];\n\n// A submission controls the received files, so bound what the trusted harness reads and reports.\nexport const MAX_COMPARED_FILE_BYTES = 8 * 1024 * 1024;\nexport const MAX_REPORTED_FILE_BYTES = 1024 * 1024;\n\nexport interface ExpectedOutputFilesComparison {\n /** Whether every file under the expected directory has a matching file in the working directory. */\n matches: boolean;\n /** Relative paths (from the working directory) of the files that are missing or different. */\n mismatchedPaths: string[];\n /**\n * `<name>_expected.<ext>` / `<name>_received.<ext>` pairs for each mismatched file, in the\n * format Exercode renders side by side. A received file that is missing, unreadable, not a\n * regular file or larger than `MAX_COMPARED_FILE_BYTES` yields only the expected entry, and a\n * file larger than `MAX_REPORTED_FILE_BYTES` is left out of the pair. Exercode decides per test case whether a learner may see these files.\n */\n outputFiles: OutputFile[];\n}\n\n/**\n * Compare the files under a test case's `.fout` directory with the files the submission wrote to\n * its working directory. Text files are compared like stdout (space-separated tokens with a\n * numeric tolerance); binary files must match byte for byte.\n */\nexport async function compareExpectedOutputFiles(\n cwd: string,\n fileOutputPath: string\n): Promise<ExpectedOutputFilesComparison> {\n const mismatchedPaths: string[] = [];\n const outputFiles: OutputFile[] = [];\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n const expectedFiles = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => ({\n absolutePath: path.join(dirent.parentPath, dirent.name),\n // POSIX separators: `requiredOutputFilePaths` and the result format use them on every platform.\n relativePath: path.posix.join(...path.relative(fileOutputPath, dirent.parentPath).split(path.sep), dirent.name),\n }))\n .toSorted((a, b) => (a.relativePath < b.relativePath ? -1 : a.relativePath > b.relativePath ? 1 : 0));\n for (const { absolutePath, relativePath } of expectedFiles) {\n // A larger expectation could never be matched by a received file, so it is an authoring error.\n const expectedStats = await fs.promises.stat(absolutePath);\n if (expectedStats.size > MAX_COMPARED_FILE_BYTES) {\n throw new Error(`expected output file ${relativePath} exceeds ${MAX_COMPARED_FILE_BYTES} bytes`);\n }\n const expected = await fs.promises.readFile(absolutePath);\n const received = await readReceivedFile(cwd, path.join(cwd, relativePath));\n if (received && fileContentsMatch(expected, received)) continue;\n\n mismatchedPaths.push(relativePath);\n // A file too large to ship in a result line is left out of the pair rather than truncated.\n if (expected.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'expected'), expected));\n }\n if (received && received.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'received'), received));\n }\n }\n return { matches: mismatchedPaths.length === 0, mismatchedPaths, outputFiles };\n}\n\n/**\n * The default verdict of the presets: `.out` decides stdout and `.fout/` decides output files, both\n * checked so a result carries every mismatch; either expectation may be absent. Returns whether the\n * run matched and the output files to report (the plain copies of mismatched required output files\n * replaced by their comparison pairs).\n */\nexport async function judgeAgainstExpectations(context: {\n stdout: string;\n expectedStdout: string | undefined;\n fileOutputPath: string | undefined;\n cwd: string;\n outputFiles: readonly OutputFile[];\n}): Promise<{ matches: boolean; outputFiles: OutputFile[] }> {\n const { stdout, expectedStdout, fileOutputPath, cwd } = context;\n let outputFiles = [...context.outputFiles];\n let matches = expectedStdout === undefined || compareStdoutAsSpaceSeparatedTokens(stdout, expectedStdout);\n if (fileOutputPath !== undefined) {\n const comparison = await compareExpectedOutputFiles(cwd, fileOutputPath);\n if (!comparison.matches) {\n matches = false;\n outputFiles = mergeComparisonOutputFiles(outputFiles, comparison);\n }\n }\n return { matches, outputFiles };\n}\n\n/**\n * Replace the plain copies of mismatched required output files with the comparison pairs, so a\n * result shows `<name>_expected.<ext>` / `<name>_received.<ext>` instead of a lone `<name>.<ext>`.\n */\nexport function mergeComparisonOutputFiles(\n outputFiles: readonly OutputFile[],\n comparison: ExpectedOutputFilesComparison\n): OutputFile[] {\n const comparisonPaths = new Set(comparison.outputFiles.map((file) => file.path));\n // The plain copy gives way to its `_received` entry; a mismatch too large for a pair keeps the\n // plain copy, and a kept file literally named like a pair entry would make the path ambiguous.\n const replacedPaths = new Set(\n comparison.mismatchedPaths.filter((filePath) => comparisonPaths.has(toComparisonPath(filePath, 'received')))\n );\n return [\n ...outputFiles.filter((file) => !replacedPaths.has(file.path) && !comparisonPaths.has(file.path)),\n ...comparison.outputFiles,\n ];\n}\n\n/** `c.txt` → `c_expected.txt`; `out/c.txt` → `out/c_expected.txt`. */\nfunction toComparisonPath(filePath: string, role: 'expected' | 'received'): string {\n const { dir, name, ext } = path.posix.parse(filePath);\n return path.posix.join(dir, `${name}_${role}${ext}`);\n}\n\n// A submission controls this path, so anything that is not a plain, readable file within the size\n// limit (a directory, a FIFO that would block, an unreadable or huge file) counts as \"not produced\".\nasync function readReceivedFile(cwd: string, receivedPath: string): Promise<Buffer | undefined> {\n // A submission-planted symlink to the expected file itself would otherwise compare equal.\n if (!(await isSafeSubmissionOutputPath(cwd, receivedPath))) return undefined;\n try {\n const stats = await fs.promises.stat(receivedPath);\n if (!stats.isFile() || stats.size > MAX_COMPARED_FILE_BYTES) return undefined;\n return await fs.promises.readFile(receivedPath);\n } catch {\n return undefined;\n }\n}\n\nfunction fileContentsMatch(expected: Buffer, received: Buffer): boolean {\n if (!isTextFile(expected)) return received.equals(expected);\n if (!isTextFile(received)) return false;\n return compareStdoutAsSpaceSeparatedTokens(received.toString('utf8'), expected.toString('utf8'));\n}\n\nconst utf8Decoder = new TextDecoder('utf-8', { fatal: true });\n\n// Valid UTF-8 without NUL bytes: a binary format that happens to decode (e.g. a PNG chunk) almost\n// always contains NUL, while text files containing U+FFFD are still treated as text.\nfunction isTextFile(data: Buffer): boolean {\n if (data.includes(0)) return false;\n try {\n utf8Decoder.decode(data);\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":"wRAYA,MAAa,EAA0B,QAC1B,EAA0B,QAqBvC,eAAsB,EACpB,EACA,EACwC,CACxC,IAAM,EAA4B,CAAC,EAC7B,EAA4B,CAAC,EAE7B,GAAgB,MADA,EAAG,SAAS,QAAQ,EAAgB,CAAE,cAAe,GAAM,UAAW,EAAK,CAAC,EAAA,CAE/F,OAAQ,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EACA,EACc,CACd,IAAM,EAAkB,IAAI,IAAI,EAAW,YAAY,IAAK,GAAS,EAAK,IAAI,CAAC,EAGzE,EAAgB,IAAI,IACxB,EAAW,gBAAgB,OAAQ,GAAa,EAAgB,IAAI,EAAiB,EAAU,UAAU,CAAC,CAAC,CAC7G,EACA,MAAO,CACL,GAAG,EAAY,OAAQ,GAAS,CAAC,EAAc,IAAI,EAAK,IAAI,GAAK,CAAC,EAAgB,IAAI,EAAK,IAAI,CAAC,EAChG,GAAG,EAAW,WAChB,CACF,CAGA,SAAS,EAAiB,EAAkB,EAAuC,CACjF,GAAM,CAAE,MAAK,OAAM,OAAQ,EAAK,MAAM,MAAM,CAAQ,EACpD,OAAO,EAAK,MAAM,KAAK,EAAK,GAAG,EAAK,GAAG,IAAO,GAAK,CACrD,CAIA,eAAe,EAAiB,EAAa,EAAmD,CAExF,SAAM,EAA2B,EAAK,CAAY,EACxD,GAAI,CACF,IAAM,EAAQ,MAAM,EAAG,SAAS,KAAK,CAAY,EAEjD,MADI,CAAC,EAAM,OAAO,GAAK,EAAM,KAAA,QAAgC,OACtD,MAAM,EAAG,SAAS,SAAS,CAAY,CAChD,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAkB,EAAkB,EAA2B,CAGtE,OAFK,EAAW,CAAQ,EACnB,EAAW,CAAQ,EACjB,EAAoC,EAAS,SAAS,MAAM,EAAG,EAAS,SAAS,MAAM,CAAC,EAD7D,GADA,EAAS,OAAO,CAAQ,CAG5D,CAEA,MAAM,EAAc,IAAI,YAAY,QAAS,CAAE,MAAO,EAAK,CAAC,EAI5D,SAAS,EAAW,EAAuB,CACzC,GAAI,EAAK,SAAS,CAAC,EAAG,MAAO,GAC7B,GAAI,CAEF,OADA,EAAY,OAAO,CAAI,EAChB,EACT,MAAQ,CACN,MAAO,EACT,CACF"}
1
+ {"version":3,"file":"compareExpectedOutputFiles.js","names":[],"sources":["../../src/helpers/compareExpectedOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { compareStdoutAsSpaceSeparatedTokens } from './compareStdoutAsSpaceSeparatedTokens.js';\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\n\ntype OutputFile = NonNullable<TestCaseResult['outputFiles']>[number];\n\n// Bound what the harness reads and reports.\nexport const MAX_COMPARED_FILE_BYTES = 8 * 1024 * 1024;\nexport const MAX_REPORTED_FILE_BYTES = 1024 * 1024;\n\nexport interface ExpectedOutputFilesComparison {\n /** Whether every file under the expected directory has a matching file in the working directory. */\n matches: boolean;\n /** Relative paths (from the working directory) of the files that are missing or different. */\n mismatchedPaths: string[];\n /**\n * `<name>_expected.<ext>` / `<name>_received.<ext>` pairs for each mismatched file, in the\n * format Exercode renders side by side. A received file that is missing, unreadable, not a\n * regular file or larger than `MAX_COMPARED_FILE_BYTES` yields only the expected entry, and a\n * file larger than `MAX_REPORTED_FILE_BYTES` is left out of the pair. Exercode decides per test case whether a learner may see these files.\n */\n outputFiles: OutputFile[];\n}\n\n/**\n * Compare the files under a test case's `.fout` directory with the files the submission wrote to\n * its working directory. Text files are compared like stdout (space-separated tokens with a\n * numeric tolerance); binary files must match byte for byte.\n */\nexport async function compareExpectedOutputFiles(\n cwd: string,\n fileOutputPath: string\n): Promise<ExpectedOutputFilesComparison> {\n const mismatchedPaths: string[] = [];\n const outputFiles: OutputFile[] = [];\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n const expectedFiles = dirents\n .filter((dirent) => dirent.isFile())\n .map((dirent) => ({\n absolutePath: path.join(dirent.parentPath, dirent.name),\n // POSIX separators: `requiredOutputFilePaths` and the result format use them on every platform.\n relativePath: path.posix.join(...path.relative(fileOutputPath, dirent.parentPath).split(path.sep), dirent.name),\n }))\n .toSorted((a, b) => (a.relativePath < b.relativePath ? -1 : a.relativePath > b.relativePath ? 1 : 0));\n for (const { absolutePath, relativePath } of expectedFiles) {\n // A larger expectation could never be matched by a received file, so it is an authoring error.\n const expectedStats = await fs.promises.stat(absolutePath);\n if (expectedStats.size > MAX_COMPARED_FILE_BYTES) {\n throw new Error(`expected output file ${relativePath} exceeds ${MAX_COMPARED_FILE_BYTES} bytes`);\n }\n const expected = await fs.promises.readFile(absolutePath);\n const received = await readReceivedFile(path.join(cwd, relativePath));\n if (received && fileContentsMatch(expected, received)) continue;\n\n mismatchedPaths.push(relativePath);\n // A file too large to ship in a result line is left out of the pair rather than truncated.\n if (expected.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'expected'), expected));\n }\n if (received && received.length <= MAX_REPORTED_FILE_BYTES) {\n outputFiles.push(encodeFileForTestCaseResult(toComparisonPath(relativePath, 'received'), received));\n }\n }\n return { matches: mismatchedPaths.length === 0, mismatchedPaths, outputFiles };\n}\n\n/**\n * The default verdict of the presets: `.out` decides stdout and `.fout/` decides output files, both\n * checked so a result carries every mismatch; either expectation may be absent. Returns whether the\n * run matched and the output files to report (the plain copies of mismatched required output files\n * replaced by their comparison pairs).\n */\nexport async function judgeAgainstExpectations(context: {\n stdout: string;\n expectedStdout: string | undefined;\n fileOutputPath: string | undefined;\n cwd: string;\n outputFiles: readonly OutputFile[];\n}): Promise<{ matches: boolean; outputFiles: OutputFile[] }> {\n const { stdout, expectedStdout, fileOutputPath, cwd } = context;\n let outputFiles = [...context.outputFiles];\n let matches = expectedStdout === undefined || compareStdoutAsSpaceSeparatedTokens(stdout, expectedStdout);\n if (fileOutputPath !== undefined) {\n const comparison = await compareExpectedOutputFiles(cwd, fileOutputPath);\n if (!comparison.matches) {\n matches = false;\n outputFiles = mergeComparisonOutputFiles(outputFiles, comparison);\n }\n }\n return { matches, outputFiles };\n}\n\n/**\n * Replace the plain copies of mismatched required output files with the comparison pairs, so a\n * result shows `<name>_expected.<ext>` / `<name>_received.<ext>` instead of a lone `<name>.<ext>`.\n */\nexport function mergeComparisonOutputFiles(\n outputFiles: readonly OutputFile[],\n comparison: ExpectedOutputFilesComparison\n): OutputFile[] {\n const comparisonPaths = new Set(comparison.outputFiles.map((file) => file.path));\n // The plain copy gives way to its `_received` entry; a mismatch too large for a pair keeps the\n // plain copy, and a kept file literally named like a pair entry would make the path ambiguous.\n const replacedPaths = new Set(\n comparison.mismatchedPaths.filter((filePath) => comparisonPaths.has(toComparisonPath(filePath, 'received')))\n );\n return [\n ...outputFiles.filter((file) => !replacedPaths.has(file.path) && !comparisonPaths.has(file.path)),\n ...comparison.outputFiles,\n ];\n}\n\n/** `c.txt` → `c_expected.txt`; `out/c.txt` → `out/c_expected.txt`. */\nfunction toComparisonPath(filePath: string, role: 'expected' | 'received'): string {\n const { dir, name, ext } = path.posix.parse(filePath);\n return path.posix.join(dir, `${name}_${role}${ext}`);\n}\n\n// Anything that is not a plain, readable file within the size limit (a directory, a FIFO that would\n// block, an unreadable or huge file) counts as \"not produced\".\nasync function readReceivedFile(receivedPath: string): Promise<Buffer | undefined> {\n try {\n const stats = await fs.promises.stat(receivedPath);\n if (!stats.isFile() || stats.size > MAX_COMPARED_FILE_BYTES) return undefined;\n return await fs.promises.readFile(receivedPath);\n } catch {\n return undefined;\n }\n}\n\nfunction fileContentsMatch(expected: Buffer, received: Buffer): boolean {\n if (!isTextFile(expected)) return received.equals(expected);\n if (!isTextFile(received)) return false;\n return compareStdoutAsSpaceSeparatedTokens(received.toString('utf8'), expected.toString('utf8'));\n}\n\nconst utf8Decoder = new TextDecoder('utf-8', { fatal: true });\n\n// Valid UTF-8 without NUL bytes: a binary format that happens to decode (e.g. a PNG chunk) almost\n// always contains NUL, while text files containing U+FFFD are still treated as text.\nfunction isTextFile(data: Buffer): boolean {\n if (data.includes(0)) return false;\n try {\n utf8Decoder.decode(data);\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":"sNAWA,MAAa,EAA0B,QAC1B,EAA0B,QAqBvC,eAAsB,EACpB,EACA,EACwC,CACxC,IAAM,EAA4B,CAAC,EAC7B,EAA4B,C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../_virtual/_rolldown/runtime.cjs"),t=require("./sandboxUser.cjs"),n=require("./safeFs.cjs");let r=require("node:fs");r=e.__toESM(r,1);async function i(e,i){if(!(await r.default.promises.lstat(e)).isDirectory())throw Error(`test case file input must be a directory, not a symlink or file: ${e}`);await n.copyWithoutFollowingSymlinks(e,i),t.makeAccessibleToSandboxUser(i)}exports.copyTestCaseFileInput=i;
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("node:fs/promises");t=e.__toESM(t,1);async function n(e,n){await t.default.cp(e,n,{force:!0,recursive:!0})}exports.copyTestCaseFileInput=n;
2
2
  //# sourceMappingURL=copyTestCaseFileInput.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"copyTestCaseFileInput.cjs","names":["fs","copyWithoutFollowingSymlinks"],"sources":["../../src/helpers/copyTestCaseFileInput.ts"],"sourcesContent":["import fs from 'node:fs';\n\nimport { copyWithoutFollowingSymlinks } from './safeFs.js';\nimport { makeAccessibleToSandboxUser } from './sandboxUser.js';\n\nexport async function copyTestCaseFileInput(fileInputPath: string, cwd: string): Promise<void> {\n // `readTestCases` only ever yields a real `.fin` directory here (it selects entries by\n // `dirent.isDirectory()`, which does not follow links), and the destination is the working\n // directory itself, so anything else would mean replacing that whole directory — with a file, or\n // with a symlink to the problem's test cases. `lstat`, not `stat`: the latter resolves a symlink\n // source and would report it as a directory.\n const fileInputStats = await fs.promises.lstat(fileInputPath);\n if (!fileInputStats.isDirectory()) {\n throw new Error(`test case file input must be a directory, not a symlink or file: ${fileInputPath}`);\n }\n // A no-follow copy: a sandboxed submission may have planted a symlink at one of these\n // destination paths to redirect this trusted-user write outside its working directory.\n await copyWithoutFollowingSymlinks(fileInputPath, cwd);\n // The copied files are owned by the harness user; the sandboxed submission must read them and\n // may create outputs in the copied directories.\n makeAccessibleToSandboxUser(cwd);\n}\n"],"mappings":"qKAKA,eAAsB,EAAsB,EAAuB,EAA4B,CAO7F,GAAI,EAAC,MADwBA,EAAAA,QAAG,SAAS,MAAM,CAAa,EAAA,CACxC,YAAY,EAC9B,MAAU,MAAM,oEAAoE,GAAe,EAIrG,MAAMC,EAAAA,6BAA6B,EAAe,CAAG,EAGrD,EAAA,4BAA4B,CAAG,CACjC"}
1
+ {"version":3,"file":"copyTestCaseFileInput.cjs","names":["fs"],"sources":["../../src/helpers/copyTestCaseFileInput.ts"],"sourcesContent":["import fs from 'node:fs/promises';\n\nexport async function copyTestCaseFileInput(fileInputPath: string, cwd: string): Promise<void> {\n await fs.cp(fileInputPath, cwd, { force: true, recursive: true });\n}\n"],"mappings":"qHAEA,eAAsB,EAAsB,EAAuB,EAA4B,CAC7F,MAAMA,EAAAA,QAAG,GAAG,EAAe,EAAK,CAAE,MAAO,GAAM,UAAW,EAAK,CAAC,CAClE"}
@@ -1,2 +1,2 @@
1
- import{makeAccessibleToSandboxUser as e}from"./sandboxUser.js";import{copyWithoutFollowingSymlinks as t}from"./safeFs.js";import n from"node:fs";async function r(r,i){if(!(await n.promises.lstat(r)).isDirectory())throw Error(`test case file input must be a directory, not a symlink or file: ${r}`);await t(r,i),e(i)}export{r as copyTestCaseFileInput};
1
+ import e from"node:fs/promises";async function t(t,n){await e.cp(t,n,{force:!0,recursive:!0})}export{t as copyTestCaseFileInput};
2
2
  //# sourceMappingURL=copyTestCaseFileInput.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"copyTestCaseFileInput.js","names":[],"sources":["../../src/helpers/copyTestCaseFileInput.ts"],"sourcesContent":["import fs from 'node:fs';\n\nimport { copyWithoutFollowingSymlinks } from './safeFs.js';\nimport { makeAccessibleToSandboxUser } from './sandboxUser.js';\n\nexport async function copyTestCaseFileInput(fileInputPath: string, cwd: string): Promise<void> {\n // `readTestCases` only ever yields a real `.fin` directory here (it selects entries by\n // `dirent.isDirectory()`, which does not follow links), and the destination is the working\n // directory itself, so anything else would mean replacing that whole directory — with a file, or\n // with a symlink to the problem's test cases. `lstat`, not `stat`: the latter resolves a symlink\n // source and would report it as a directory.\n const fileInputStats = await fs.promises.lstat(fileInputPath);\n if (!fileInputStats.isDirectory()) {\n throw new Error(`test case file input must be a directory, not a symlink or file: ${fileInputPath}`);\n }\n // A no-follow copy: a sandboxed submission may have planted a symlink at one of these\n // destination paths to redirect this trusted-user write outside its working directory.\n await copyWithoutFollowingSymlinks(fileInputPath, cwd);\n // The copied files are owned by the harness user; the sandboxed submission must read them and\n // may create outputs in the copied directories.\n makeAccessibleToSandboxUser(cwd);\n}\n"],"mappings":"iJAKA,eAAsB,EAAsB,EAAuB,EAA4B,CAO7F,GAAI,EAAC,MADwB,EAAG,SAAS,MAAM,CAAa,EAAA,CACxC,YAAY,EAC9B,MAAU,MAAM,oEAAoE,GAAe,EAIrG,MAAM,EAA6B,EAAe,CAAG,EAGrD,EAA4B,CAAG,CACjC"}
1
+ {"version":3,"file":"copyTestCaseFileInput.js","names":[],"sources":["../../src/helpers/copyTestCaseFileInput.ts"],"sourcesContent":["import fs from 'node:fs/promises';\n\nexport async function copyTestCaseFileInput(fileInputPath: string, cwd: string): Promise<void> {\n await fs.cp(fileInputPath, cwd, { force: true, recursive: true });\n}\n"],"mappings":"gCAEA,eAAsB,EAAsB,EAAuB,EAA4B,CAC7F,MAAM,EAAG,GAAG,EAAe,EAAK,CAAE,MAAO,GAAM,UAAW,EAAK,CAAC,CAClE"}
@@ -1,14 +1,14 @@
1
- "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./removeCommentsInSourceCode.cjs"),n=require("../types/decisionCode.cjs"),r=require("../types/problem.cjs"),i=require("./findLanguageDefinitionByPath.cjs");let a=require("node:fs");a=e.__toESM(a,1);let o=require("node:path");o=e.__toESM(o,1);async function s(e,s){let l=new Set,u=[];for(let n of await a.default.promises.readdir(e,{withFileTypes:!0,recursive:!0})){if(!n.isFile())continue;let r=o.default.relative(e,o.default.join(n.parentPath,n.name));l.add(r);let s=await a.default.promises.readFile(o.default.join(n.parentPath,n.name),`utf8`);if(s.includes(`�`))continue;let c=i.findLanguageDefinitionByPath(n.name);c&&u.push({path:r,data:c.grammer?t.removeCommentsInSourceCode(c.grammer,s):s})}if(s.requiredSubmissionFilePaths){let e=s.requiredSubmissionFilePaths.filter(e=>!l.has(e)).toSorted();if(e.length>0)return{decisionCode:n.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,feedbackMarkdown:`ファイルが不足しています。
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./removeCommentsInSourceCode.cjs"),n=require("../types/problem.cjs"),r=require("./findLanguageDefinitionByPath.cjs"),i=require("../types/decisionCode.cjs");let a=require("node:fs");a=e.__toESM(a,1);let o=require("node:path");o=e.__toESM(o,1);async function s(e,s){let l=new Set,u=[];for(let n of await a.default.promises.readdir(e,{withFileTypes:!0,recursive:!0})){if(!n.isFile())continue;let i=o.default.relative(e,o.default.join(n.parentPath,n.name));l.add(i);let s=await a.default.promises.readFile(o.default.join(n.parentPath,n.name),`utf8`);if(s.includes(`�`))continue;let c=r.findLanguageDefinitionByPath(n.name);c&&u.push({path:i,data:c.grammer?t.removeCommentsInSourceCode(c.grammer,s):s})}if(s.requiredSubmissionFilePaths){let e=s.requiredSubmissionFilePaths.filter(e=>!l.has(e)).toSorted();if(e.length>0)return{decisionCode:i.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,feedbackMarkdown:`ファイルが不足しています。
2
2
  次のファイルを追加してから再度提出してください。
3
3
 
4
4
  ${e.map(e=>`- \`${e}\``).join(`
5
5
  `)}
6
- `}}let d=[];for(let e of s.forbiddenRegExpsInCode??[]){let{pattern:t,message:n}=r.normalizeCodeRule(e),i=new RegExp(t,`g`),a=u.flatMap(e=>[...e.data.matchAll(i)].map(t=>({path:e.path,match:t[0]})));a.length>0&&d.push({label:n??`禁止パターン \`${i.toString()}\``,matches:a})}for(let e of s.forbiddenTextsInCode??[]){let{pattern:t,message:n}=r.normalizeCodeRule(e),i=u.filter(e=>e.data.includes(t)).map(e=>({path:e.path,match:t}));i.length>0&&d.push({label:n??`禁止文字列 \`${t}\``,matches:i})}if(d.length>0)return{decisionCode:n.DecisionCode.FORBIDDEN_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に禁止された文字列が含まれています。
6
+ `}}let d=[];for(let e of s.forbiddenRegExpsInCode??[]){let{pattern:t,message:r}=n.normalizeCodeRule(e),i=new RegExp(t,`g`),a=u.flatMap(e=>[...e.data.matchAll(i)].map(t=>({path:e.path,match:t[0]})));a.length>0&&d.push({label:r??`禁止パターン \`${i.toString()}\``,matches:a})}for(let e of s.forbiddenTextsInCode??[]){let{pattern:t,message:r}=n.normalizeCodeRule(e),i=u.filter(e=>e.data.includes(t)).map(e=>({path:e.path,match:t}));i.length>0&&d.push({label:r??`禁止文字列 \`${t}\``,matches:i})}if(d.length>0)return{decisionCode:i.DecisionCode.FORBIDDEN_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に禁止された文字列が含まれています。
7
7
  ソースコードを修正してから再度提出してください。
8
8
 
9
9
  ${d.map(c).join(`
10
10
  `)}
11
- `};let f=[];for(let e of s.requiredRegExpsInCode??[]){let{pattern:t,message:n}=r.normalizeCodeRule(e),i=new RegExp(t);u.some(e=>i.test(e.data))||f.push(n??`\`${i.toString()}\``)}if(f.length>0)return{decisionCode:n.DecisionCode.REQUIRED_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に必要な文字列が含まれていません。
11
+ `};let f=[];for(let e of s.requiredRegExpsInCode??[]){let{pattern:t,message:r}=n.normalizeCodeRule(e),i=new RegExp(t);u.some(e=>i.test(e.data))||f.push(r??`\`${i.toString()}\``)}if(f.length>0)return{decisionCode:i.DecisionCode.REQUIRED_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に必要な文字列が含まれていません。
12
12
  ソースコードを修正してから再度提出してください。
13
13
 
14
14
  ${f.map(e=>`- ${e}`).join(`
@@ -1,14 +1,14 @@
1
- import{removeCommentsInSourceCode as e}from"./removeCommentsInSourceCode.js";import{DecisionCode as t}from"../types/decisionCode.js";import{normalizeCodeRule as n}from"../types/problem.js";import{findLanguageDefinitionByPath as r}from"./findLanguageDefinitionByPath.js";import i from"node:fs";import a from"node:path";async function o(o,c){let l=new Set,u=[];for(let t of await i.promises.readdir(o,{withFileTypes:!0,recursive:!0})){if(!t.isFile())continue;let n=a.relative(o,a.join(t.parentPath,t.name));l.add(n);let s=await i.promises.readFile(a.join(t.parentPath,t.name),`utf8`);if(s.includes(`�`))continue;let c=r(t.name);c&&u.push({path:n,data:c.grammer?e(c.grammer,s):s})}if(c.requiredSubmissionFilePaths){let e=c.requiredSubmissionFilePaths.filter(e=>!l.has(e)).toSorted();if(e.length>0)return{decisionCode:t.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,feedbackMarkdown:`ファイルが不足しています。
1
+ import{removeCommentsInSourceCode as e}from"./removeCommentsInSourceCode.js";import{normalizeCodeRule as t}from"../types/problem.js";import{findLanguageDefinitionByPath as n}from"./findLanguageDefinitionByPath.js";import{DecisionCode as r}from"../types/decisionCode.js";import i from"node:fs";import a from"node:path";async function o(o,c){let l=new Set,u=[];for(let t of await i.promises.readdir(o,{withFileTypes:!0,recursive:!0})){if(!t.isFile())continue;let r=a.relative(o,a.join(t.parentPath,t.name));l.add(r);let s=await i.promises.readFile(a.join(t.parentPath,t.name),`utf8`);if(s.includes(`�`))continue;let c=n(t.name);c&&u.push({path:r,data:c.grammer?e(c.grammer,s):s})}if(c.requiredSubmissionFilePaths){let e=c.requiredSubmissionFilePaths.filter(e=>!l.has(e)).toSorted();if(e.length>0)return{decisionCode:r.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,feedbackMarkdown:`ファイルが不足しています。
2
2
  次のファイルを追加してから再度提出してください。
3
3
 
4
4
  ${e.map(e=>`- \`${e}\``).join(`
5
5
  `)}
6
- `}}let d=[];for(let e of c.forbiddenRegExpsInCode??[]){let{pattern:t,message:r}=n(e),i=new RegExp(t,`g`),a=u.flatMap(e=>[...e.data.matchAll(i)].map(t=>({path:e.path,match:t[0]})));a.length>0&&d.push({label:r??`禁止パターン \`${i.toString()}\``,matches:a})}for(let e of c.forbiddenTextsInCode??[]){let{pattern:t,message:r}=n(e),i=u.filter(e=>e.data.includes(t)).map(e=>({path:e.path,match:t}));i.length>0&&d.push({label:r??`禁止文字列 \`${t}\``,matches:i})}if(d.length>0)return{decisionCode:t.FORBIDDEN_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に禁止された文字列が含まれています。
6
+ `}}let d=[];for(let e of c.forbiddenRegExpsInCode??[]){let{pattern:n,message:r}=t(e),i=new RegExp(n,`g`),a=u.flatMap(e=>[...e.data.matchAll(i)].map(t=>({path:e.path,match:t[0]})));a.length>0&&d.push({label:r??`禁止パターン \`${i.toString()}\``,matches:a})}for(let e of c.forbiddenTextsInCode??[]){let{pattern:n,message:r}=t(e),i=u.filter(e=>e.data.includes(n)).map(e=>({path:e.path,match:n}));i.length>0&&d.push({label:r??`禁止文字列 \`${n}\``,matches:i})}if(d.length>0)return{decisionCode:r.FORBIDDEN_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に禁止された文字列が含まれています。
7
7
  ソースコードを修正してから再度提出してください。
8
8
 
9
9
  ${d.map(s).join(`
10
10
  `)}
11
- `};let f=[];for(let e of c.requiredRegExpsInCode??[]){let{pattern:t,message:r}=n(e),i=new RegExp(t);u.some(e=>i.test(e.data))||f.push(r??`\`${i.toString()}\``)}if(f.length>0)return{decisionCode:t.REQUIRED_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に必要な文字列が含まれていません。
11
+ `};let f=[];for(let e of c.requiredRegExpsInCode??[]){let{pattern:n,message:r}=t(e),i=new RegExp(n);u.some(e=>i.test(e.data))||f.push(r??`\`${i.toString()}\``)}if(f.length>0)return{decisionCode:r.REQUIRED_PATTERNS_IN_CODE_ERROR,feedbackMarkdown:`ソースコード中に必要な文字列が含まれていません。
12
12
  ソースコードを修正してから再度提出してください。
13
13
 
14
14
  ${f.map(e=>`- ${e}`).join(`
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./printTestCaseResult.cjs"),n=require("./sandboxUser.cjs"),r=require("./safeFs.cjs");let i=require("node:fs");i=e.__toESM(i,1);let a=require("node:path");a=e.__toESM(a,1);async function o(e,n){let r=[];for(let o of n)try{let n=a.default.join(e,o);if(!await s(e,n))continue;let c=await i.default.promises.readFile(n);r.push(t.encodeFileForTestCaseResult(o,c))}catch{}return r}async function s(e,t){if(!n.sandboxUserName)return!0;try{let n=await i.default.promises.realpath(t),a=await i.default.promises.realpath(e);return r.isContainedPath(a,n)}catch{return!1}}exports.isSafeSubmissionOutputPath=s,exports.readOutputFiles=o;
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./printTestCaseResult.cjs");let n=require("node:fs");n=e.__toESM(n,1);let r=require("node:path");r=e.__toESM(r,1);async function i(e,i){let a=[];for(let o of i)try{let i=await n.default.promises.readFile(r.default.join(e,o));a.push(t.encodeFileForTestCaseResult(o,i))}catch{}return a}exports.readOutputFiles=i;
2
2
  //# sourceMappingURL=readOutputFiles.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"readOutputFiles.cjs","names":["path","fs","encodeFileForTestCaseResult","sandboxUserName","isContainedPath"],"sources":["../../src/helpers/readOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\nimport { isContainedPath } from './safeFs.js';\nimport { sandboxUserName } from './sandboxUser.js';\n\nexport async function readOutputFiles(\n cwd: string,\n outputFilePaths: readonly string[]\n): Promise<NonNullable<TestCaseResult['outputFiles']>> {\n const outputFiles: NonNullable<TestCaseResult['outputFiles']> = [];\n for (const filePath of outputFilePaths) {\n try {\n const resolvedPath = path.join(cwd, filePath);\n if (!(await isSafeSubmissionOutputPath(cwd, resolvedPath))) continue;\n const buffer = await fs.promises.readFile(resolvedPath);\n outputFiles.push(encodeFileForTestCaseResult(filePath, buffer));\n } catch {\n // file not found\n }\n }\n return outputFiles;\n}\n\n/**\n * Whether the harness may read the given submission-created path. When submissions run as the\n * sandbox user while the harness is trusted, a submission could plant a symlink (or a symlinked\n * parent directory) escaping its working directory — e.g. to the 0700 problem directory — and the\n * privileged read would exfiltrate protected bytes, so only paths that resolve inside the working\n * directory are allowed. Without user separation the submission can read those targets itself, so\n * the check is skipped to keep authoring behavior unchanged.\n */\nexport async function isSafeSubmissionOutputPath(cwd: string, filePath: string): Promise<boolean> {\n if (!sandboxUserName) return true;\n try {\n const realFilePath = await fs.promises.realpath(filePath);\n const realCwd = await fs.promises.realpath(cwd);\n return isContainedPath(realCwd, realFilePath);\n } catch {\n return false;\n }\n}\n"],"mappings":"wPASA,eAAsB,EACpB,EACA,EACqD,CACrD,IAAM,EAA0D,CAAC,EACjE,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAeA,EAAAA,QAAK,KAAK,EAAK,CAAQ,EAC5C,GAAI,CAAE,MAAM,EAA2B,EAAK,CAAY,EAAI,SAC5D,IAAM,EAAS,MAAMC,EAAAA,QAAG,SAAS,SAAS,CAAY,EACtD,EAAY,KAAKC,EAAAA,4BAA4B,EAAU,CAAM,CAAC,CAChE,MAAQ,CAER,CAEF,OAAO,CACT,CAUA,eAAsB,EAA2B,EAAa,EAAoC,CAChG,GAAI,CAACC,EAAAA,gBAAiB,MAAO,GAC7B,GAAI,CACF,IAAM,EAAe,MAAMF,EAAAA,QAAG,SAAS,SAAS,CAAQ,EAClD,EAAU,MAAMA,EAAAA,QAAG,SAAS,SAAS,CAAG,EAC9C,OAAOG,EAAAA,gBAAgB,EAAS,CAAY,CAC9C,MAAQ,CACN,MAAO,EACT,CACF"}
1
+ {"version":3,"file":"readOutputFiles.cjs","names":["fs","path","encodeFileForTestCaseResult"],"sources":["../../src/helpers/readOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\n\nexport async function readOutputFiles(\n cwd: string,\n outputFilePaths: readonly string[]\n): Promise<NonNullable<TestCaseResult['outputFiles']>> {\n const outputFiles: NonNullable<TestCaseResult['outputFiles']> = [];\n for (const filePath of outputFilePaths) {\n try {\n // Read as-is on purpose: the submission runs as the same OS user as this harness, so a symlink\n // only reaches what it can already read, and a planted FIFO only stalls its own run, which the\n // judge server's request timeout ends.\n const buffer = await fs.promises.readFile(path.join(cwd, filePath));\n outputFiles.push(encodeFileForTestCaseResult(filePath, buffer));\n } catch {\n // file not found\n }\n }\n return outputFiles;\n}\n"],"mappings":"+LAOA,eAAsB,EACpB,EACA,EACqD,CACrD,IAAM,EAA0D,CAAC,EACjE,IAAK,IAAM,KAAY,EACrB,GAAI,CAIF,IAAM,EAAS,MAAMA,EAAAA,QAAG,SAAS,SAASC,EAAAA,QAAK,KAAK,EAAK,CAAQ,CAAC,EAClE,EAAY,KAAKC,EAAAA,4BAA4B,EAAU,CAAM,CAAC,CAChE,MAAQ,CAER,CAEF,OAAO,CACT"}
@@ -1,11 +1,2 @@
1
1
  import type { TestCaseResult } from '../types/testCaseResult.js';
2
2
  export declare function readOutputFiles(cwd: string, outputFilePaths: readonly string[]): Promise<NonNullable<TestCaseResult['outputFiles']>>;
3
- /**
4
- * Whether the harness may read the given submission-created path. When submissions run as the
5
- * sandbox user while the harness is trusted, a submission could plant a symlink (or a symlinked
6
- * parent directory) escaping its working directory — e.g. to the 0700 problem directory — and the
7
- * privileged read would exfiltrate protected bytes, so only paths that resolve inside the working
8
- * directory are allowed. Without user separation the submission can read those targets itself, so
9
- * the check is skipped to keep authoring behavior unchanged.
10
- */
11
- export declare function isSafeSubmissionOutputPath(cwd: string, filePath: string): Promise<boolean>;
@@ -1,2 +1,2 @@
1
- import{encodeFileForTestCaseResult as e}from"./printTestCaseResult.js";import{sandboxUserName as t}from"./sandboxUser.js";import{isContainedPath as n}from"./safeFs.js";import r from"node:fs";import i from"node:path";async function a(t,n){let a=[];for(let s of n)try{let n=i.join(t,s);if(!await o(t,n))continue;let c=await r.promises.readFile(n);a.push(e(s,c))}catch{}return a}async function o(e,i){if(!t)return!0;try{let t=await r.promises.realpath(i),a=await r.promises.realpath(e);return n(a,t)}catch{return!1}}export{o as isSafeSubmissionOutputPath,a as readOutputFiles};
1
+ import{encodeFileForTestCaseResult as e}from"./printTestCaseResult.js";import t from"node:fs";import n from"node:path";async function r(r,i){let a=[];for(let o of i)try{let i=await t.promises.readFile(n.join(r,o));a.push(e(o,i))}catch{}return a}export{r as readOutputFiles};
2
2
  //# sourceMappingURL=readOutputFiles.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"readOutputFiles.js","names":[],"sources":["../../src/helpers/readOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\nimport { isContainedPath } from './safeFs.js';\nimport { sandboxUserName } from './sandboxUser.js';\n\nexport async function readOutputFiles(\n cwd: string,\n outputFilePaths: readonly string[]\n): Promise<NonNullable<TestCaseResult['outputFiles']>> {\n const outputFiles: NonNullable<TestCaseResult['outputFiles']> = [];\n for (const filePath of outputFilePaths) {\n try {\n const resolvedPath = path.join(cwd, filePath);\n if (!(await isSafeSubmissionOutputPath(cwd, resolvedPath))) continue;\n const buffer = await fs.promises.readFile(resolvedPath);\n outputFiles.push(encodeFileForTestCaseResult(filePath, buffer));\n } catch {\n // file not found\n }\n }\n return outputFiles;\n}\n\n/**\n * Whether the harness may read the given submission-created path. When submissions run as the\n * sandbox user while the harness is trusted, a submission could plant a symlink (or a symlinked\n * parent directory) escaping its working directory — e.g. to the 0700 problem directory — and the\n * privileged read would exfiltrate protected bytes, so only paths that resolve inside the working\n * directory are allowed. Without user separation the submission can read those targets itself, so\n * the check is skipped to keep authoring behavior unchanged.\n */\nexport async function isSafeSubmissionOutputPath(cwd: string, filePath: string): Promise<boolean> {\n if (!sandboxUserName) return true;\n try {\n const realFilePath = await fs.promises.realpath(filePath);\n const realCwd = await fs.promises.realpath(cwd);\n return isContainedPath(realCwd, realFilePath);\n } catch {\n return false;\n }\n}\n"],"mappings":"wNASA,eAAsB,EACpB,EACA,EACqD,CACrD,IAAM,EAA0D,CAAC,EACjE,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAe,EAAK,KAAK,EAAK,CAAQ,EAC5C,GAAI,CAAE,MAAM,EAA2B,EAAK,CAAY,EAAI,SAC5D,IAAM,EAAS,MAAM,EAAG,SAAS,SAAS,CAAY,EACtD,EAAY,KAAK,EAA4B,EAAU,CAAM,CAAC,CAChE,MAAQ,CAER,CAEF,OAAO,CACT,CAUA,eAAsB,EAA2B,EAAa,EAAoC,CAChG,GAAI,CAAC,EAAiB,MAAO,GAC7B,GAAI,CACF,IAAM,EAAe,MAAM,EAAG,SAAS,SAAS,CAAQ,EAClD,EAAU,MAAM,EAAG,SAAS,SAAS,CAAG,EAC9C,OAAO,EAAgB,EAAS,CAAY,CAC9C,MAAQ,CACN,MAAO,EACT,CACF"}
1
+ {"version":3,"file":"readOutputFiles.js","names":[],"sources":["../../src/helpers/readOutputFiles.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { TestCaseResult } from '../types/testCaseResult.js';\n\nimport { encodeFileForTestCaseResult } from './printTestCaseResult.js';\n\nexport async function readOutputFiles(\n cwd: string,\n outputFilePaths: readonly string[]\n): Promise<NonNullable<TestCaseResult['outputFiles']>> {\n const outputFiles: NonNullable<TestCaseResult['outputFiles']> = [];\n for (const filePath of outputFilePaths) {\n try {\n // Read as-is on purpose: the submission runs as the same OS user as this harness, so a symlink\n // only reaches what it can already read, and a planted FIFO only stalls its own run, which the\n // judge server's request timeout ends.\n const buffer = await fs.promises.readFile(path.join(cwd, filePath));\n outputFiles.push(encodeFileForTestCaseResult(filePath, buffer));\n } catch {\n // file not found\n }\n }\n return outputFiles;\n}\n"],"mappings":"uHAOA,eAAsB,EACpB,EACA,EACqD,CACrD,IAAM,EAA0D,CAAC,EACjE,IAAK,IAAM,KAAY,EACrB,GAAI,CAIF,IAAM,EAAS,MAAM,EAAG,SAAS,SAAS,EAAK,KAAK,EAAK,CAAQ,CAAC,EAClE,EAAY,KAAK,EAA4B,EAAU,CAAM,CAAC,CAChE,MAAQ,CAER,CAEF,OAAO,CACT"}
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./sandboxUser.cjs"),n=require("./safeFs.cjs");let r=require("node:fs");r=e.__toESM(r,1);let i=require("node:path");i=e.__toESM(i,1);let a=require("node:child_process");a=e.__toESM(a,1);let o=require("node:os");o=e.__toESM(o,1);let s=require("node:fs/promises");s=e.__toESM(s,1);const c={bun:[`package.json`,`bun.lock`,`bun.lockb`],cargo:[`Cargo.toml`,`Cargo.lock`],go:[`go.mod`,`go.sum`],gradle:[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradle.properties`,`gradle.lockfile`,`buildscript-gradle.lockfile`,`gradle`,`gradlew`,`gradlew.bat`],maven:[`pom.xml`,`.mvn`,`mvnw`,`mvnw.cmd`],npm:[`package.json`,`package-lock.json`],pnpm:[`package.json`,`pnpm-lock.yaml`,`pnpm-workspace.yaml`],ruby:[`Gemfile`,`Gemfile.lock`,`.ruby-version`],uv:[`pyproject.toml`,`uv.lock`],yarn:[`package.json`,`yarn.lock`,`.yarnrc`,`.yarnrc.yml`,`.yarn`]},l={bun:h,cargo:g,go:_,gradle:v,maven:y,npm:b,pnpm:x,ruby:S,uv:C,yarn:w},u=M();async function d(e){let n=await s.default.mkdtemp(i.default.join(o.default.tmpdir(),e.tempDirPrefix??`exercode-`));try{await s.default.cp(e.cwd,n,{recursive:!0}),await k({packageManager:e.packageManager,projectDir:e.projectDir,runDir:n,projectFilePaths:e.projectFilePaths}),t.makeAccessibleToSandboxUser(n);let r=e.env?{...process.env,...e.env}:process.env,i=e.prepareDependencies===!1?void 0:await p(e.packageManager,n),a=typeof e.command==`function`?e.command({runDir:n}):e.command,o=Date.now(),c=e.outputLimitBytes??52428800,l;if(i&&(l=await j(i,{cwd:n,env:r,outputLimitBytes:c,stdin:``,timeLimitSeconds:e.timeLimitSeconds}),m(l)))return f({elapsedTimeSeconds:(Date.now()-o)/1e3,options:e,result:l});let u=e.timeLimitSeconds-(Date.now()-o)/1e3;if(u<=0)return{stdin:e.stdin??``,stdout:l?.stdout??``,stderr:l?.stderr??``,status:0,timeSeconds:e.timeLimitSeconds+.001,memoryBytes:l?.memoryBytes??0,timedOut:!0,signal:l?.signal,outputLimitExceeded:!1};let d=await j(a,{cwd:n,env:r,outputLimitBytes:c,stdin:e.stdin??``,timeLimitSeconds:u}),h=(Date.now()-o)/1e3;return f(l?{elapsedTimeSeconds:h,options:e,result:{...d,timeSeconds:l.timeSeconds+d.timeSeconds,memoryBytes:Math.max(l.memoryBytes,d.memoryBytes)}}:{elapsedTimeSeconds:h,options:e,result:d})}finally{try{t.sandboxUserName&&t.killSandboxUserProcesses()}finally{await t.forceRemove(n)}}}function f(e){return{stdin:e.options.stdin??``,stdout:e.result.stdout,stderr:e.result.stderr,status:e.result.timedOut||e.result.outputLimitExceeded?0:e.result.status,timeSeconds:e.result.timedOut?e.options.timeLimitSeconds+.001:e.result.timeSeconds||e.elapsedTimeSeconds,memoryBytes:e.result.memoryBytes,timedOut:e.result.timedOut,signal:e.result.signal,outputLimitExceeded:e.result.outputLimitExceeded}}function p(e,t){return l[e](t)}function m(e){return e.status!==0||e.timedOut||e.outputLimitExceeded}async function h(e){if(await D(i.default.join(e,`package.json`)))return await E(e,[`bun.lock`,`bun.lockb`])?[`bun`,`install`,`--frozen-lockfile`,`--silent`]:[`bun`,`install`,`--silent`]}async function g(e){if(await D(i.default.join(e,`Cargo.toml`)))return await D(i.default.join(e,`Cargo.lock`))?[`cargo`,`fetch`,`--locked`]:[`cargo`,`fetch`]}async function _(e){if(await D(i.default.join(e,`go.mod`)))return[`go`,`mod`,`download`]}async function v(e){if(!await E(e,[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradlew`,`gradlew.bat`]))return;let t=[`--no-daemon`,`--quiet`,`dependencies`];return process.platform===`win32`?await D(i.default.join(e,`gradlew.bat`))?[`cmd.exe`,`/c`,`gradlew.bat`,...t]:[`gradle`,...t]:await D(i.default.join(e,`gradlew`))?[`sh`,`./gradlew`,...t]:[`gradle`,...t]}async function y(e){if(!await D(i.default.join(e,`pom.xml`)))return;let t=[`-q`,`dependency:go-offline`];return process.platform===`win32`?await D(i.default.join(e,`mvnw.cmd`))?[`cmd.exe`,`/c`,`mvnw.cmd`,...t]:[`mvn`,...t]:await D(i.default.join(e,`mvnw`))?[`sh`,`./mvnw`,...t]:[`mvn`,...t]}async function b(e){if(await D(i.default.join(e,`package.json`)))return await D(i.default.join(e,`package-lock.json`))?[`npm`,`ci`,`--silent`]:[`npm`,`install`,`--silent`]}async function x(e){if(await D(i.default.join(e,`package.json`)))return await D(i.default.join(e,`pnpm-lock.yaml`))?[`pnpm`,`install`,`--frozen-lockfile`,`--silent`]:[`pnpm`,`install`,`--silent`]}async function S(e){if(await D(i.default.join(e,`Gemfile`)))return await D(i.default.join(e,`Gemfile.lock`))?[`bundle`,`install`,`--frozen`,`--quiet`]:[`bundle`,`install`,`--quiet`]}async function C(){}async function w(e){if(!await D(i.default.join(e,`package.json`)))return;let t=await T(e),n=await D(i.default.join(e,`yarn.lock`));return t?n?[`yarn`,`install`,`--immutable`]:[`yarn`,`install`]:n?[`yarn`,`install`,`--frozen-lockfile`,`--silent`]:[`yarn`,`install`,`--silent`]}async function T(e){if(await D(i.default.join(e,`.yarnrc.yml`)))return!0;let t=await O(i.default.join(e,`package.json`)),n=typeof t.packageManager==`string`?t.packageManager:void 0,r=/^yarn@(\d+)/.exec(n??``)?.[1];return r!==void 0&&Number(r)>=2}async function E(e,t){for(let n of t)if(await D(i.default.join(e,n)))return!0;return!1}async function D(e){try{return await s.default.access(e),!0}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e;return!1}}async function O(e){try{let t=JSON.parse(await s.default.readFile(e,`utf8`));return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch(e){if(e instanceof SyntaxError||(typeof e==`object`&&e&&`code`in e?e.code:void 0)===`ENOENT`)return{};throw e}}async function k(e){for(let t of e.projectFilePaths??c[e.packageManager])await A(i.default.join(e.projectDir,t),i.default.join(e.runDir,t),e.runDir)}async function A(e,t,r){try{await s.default.lstat(e),await n.createDirectoryWithoutFollowingSymlinks(r,i.default.dirname(t)),await n.copyWithoutFollowingSymlinks(e,t)}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e}}async function j(e,n){let r=u===void 0?void 0:i.default.join(n.cwd,`.exercode-time-result`),o=t.wrapCommandWithSandboxUser(e),s=u===void 0?o:t.prependInsideSandboxWrapper(o,[...u,`--output=${r}`]),c=t.startSandboxTimeoutWatchdog(n.timeLimitSeconds),l=Date.now()+(Math.ceil(n.timeLimitSeconds)+5)*1e3,d;try{d=a.default.spawn(s[0],s.slice(1),{cwd:n.cwd,detached:process.platform!==`win32`,env:{...n.env,...t.getSandboxUserEnvOverrides(n.env)},stdio:[`pipe`,`pipe`,`pipe`]})}catch(e){throw c.cancel(),e}let f=[],p=[],m=0,h=!1,g=!1,_,v,y=e=>{try{N(d,e)}catch(e){_??=e instanceof Error?e:Error(String(e)),v?.()}},b=(e,t)=>{if(m>=n.outputLimitBytes){t.byteLength>0&&(g=!0,y(`SIGKILL`));return}let r=n.outputLimitBytes-m,i=t.byteLength>r?t.subarray(0,r):t;e.push(i),m+=i.byteLength,t.byteLength>r&&(g=!0,y(`SIGKILL`))};d.stdout.on(`data`,e=>b(f,e)),d.stderr.on(`data`,e=>b(p,e));let x=setTimeout(()=>{h=!0,y(`SIGTERM`)},n.timeLimitSeconds*1e3),S=setTimeout(()=>{h&&y(`SIGKILL`)},n.timeLimitSeconds*1e3+1e3);S.unref();let C,w=!1,{status:T,signal:E}=await new Promise((e,t)=>{let r=!1,i,a=e=>{r||(i=e,y(`SIGKILL`),d.pid===void 0&&(r=!0,t(e)))};v=()=>{C??=setTimeout(()=>{r||(r=!0,t(_??Error(`failed to terminate the submission`)))},Math.max(0,l-Date.now())+2e3)},d.on(`error`,a),d.stdin.on(`error`,e=>{e.code!==`EPIPE`&&a(e)}),d.on(`close`,(n,a)=>{if(!r){if(r=!0,w=!0,i){t(i);return}e({status:n??void 0,signal:a??void 0})}}),d.stdin.end(n.stdin)}).finally(()=>{clearTimeout(x),clearTimeout(S),C&&clearTimeout(C),(w||!_)&&c.cancel()}),{timeSeconds:D,memoryBytes:O}=r===void 0?{timeSeconds:0,memoryBytes:0}:await F(r);return{stdout:Buffer.concat(f).toString(),stderr:Buffer.concat(p).toString(),status:T,timeSeconds:D,memoryBytes:O,timedOut:h,signal:E,outputLimitExceeded:g}}function M(){let e=o.default.platform()===`darwin`?`gtime`:`/usr/bin/time`,t=a.default.spawnSync(e,[`--version`],{stdio:`ignore`});if(!(t.error||t.status!==0))return[e,`--format`,`%e %M`]}function N(e,n){if(e.pid!==void 0){if(t.sandboxUserName){t.killSandboxUserProcesses([n===`SIGKILL`?`KILL`:`TERM`]);return}try{if(process.platform===`win32`){e.kill(n);return}process.kill(-e.pid,n)}catch(e){let t=typeof e==`object`&&e&&`code`in e?e.code:void 0;if(t!==`ESRCH`&&t!==`EPERM`)throw e}}}function P(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function F(e){let t,n;try{if(n=await s.default.open(e,r.default.constants.O_RDONLY|r.default.constants.O_NOFOLLOW|r.default.constants.O_NONBLOCK),!(await n.stat()).isFile())throw Error(`${e} is not a regular file`);t=await n.readFile(`utf8`)}catch(t){if(P(t,`ENOENT`))return{timeSeconds:0,memoryBytes:0};throw Error(`failed to read the time measurement at ${e}`,{cause:t})}finally{await n?.close()}let i=/(\d+(?:[.,]\d+)?) (\d+)\s*$/.exec(t);return i?{timeSeconds:Number(i[1].replace(`,`,`.`)),memoryBytes:Number(i[2])*1024}:{timeSeconds:0,memoryBytes:0}}exports.copyPackageManagerProjectFiles=k,exports.runCommandInTemporaryPackageManagerProject=d;
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./temporaryProblemDirCopy.cjs");let n=require("node:path");n=e.__toESM(n,1);let r=require("node:fs/promises");r=e.__toESM(r,1);let i=require("node:child_process");i=e.__toESM(i,1);let a=require("node:os");a=e.__toESM(a,1);const o={bun:[`package.json`,`bun.lock`,`bun.lockb`],cargo:[`Cargo.toml`,`Cargo.lock`],go:[`go.mod`,`go.sum`],gradle:[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradle.properties`,`gradle.lockfile`,`buildscript-gradle.lockfile`,`gradle`,`gradlew`,`gradlew.bat`],maven:[`pom.xml`,`.mvn`,`mvnw`,`mvnw.cmd`],npm:[`package.json`,`package-lock.json`],pnpm:[`package.json`,`pnpm-lock.yaml`,`pnpm-workspace.yaml`],ruby:[`Gemfile`,`Gemfile.lock`,`.ruby-version`],uv:[`pyproject.toml`,`uv.lock`],yarn:[`package.json`,`yarn.lock`,`.yarnrc`,`.yarnrc.yml`,`.yarn`]},s={bun:p,cargo:m,go:h,gradle:g,maven:_,npm:v,pnpm:y,ruby:b,uv:x,yarn:S},c=A();async function l(e){let i=await r.default.mkdtemp(n.default.join(a.default.tmpdir(),e.tempDirPrefix??`exercode-`));try{await r.default.cp(e.cwd,i,{recursive:!0}),await D({packageManager:e.packageManager,projectDir:e.projectDir,runDir:i,projectFilePaths:e.projectFilePaths});let t=e.env?{...process.env,...e.env}:process.env,n=e.prepareDependencies===!1?void 0:await d(e.packageManager,i),a=typeof e.command==`function`?e.command({runDir:i}):e.command,o=Date.now(),s=e.outputLimitBytes??52428800,c;if(n&&(c=await k(n,{cwd:i,env:t,outputLimitBytes:s,stdin:``,timeLimitSeconds:e.timeLimitSeconds}),f(c)))return u({elapsedTimeSeconds:(Date.now()-o)/1e3,options:e,result:c});let l=e.timeLimitSeconds-(Date.now()-o)/1e3;if(l<=0)return{stdin:e.stdin??``,stdout:c?.stdout??``,stderr:c?.stderr??``,status:0,timeSeconds:e.timeLimitSeconds+.001,memoryBytes:c?.memoryBytes??0,timedOut:!0,signal:c?.signal,outputLimitExceeded:!1};let p=await k(a,{cwd:i,env:t,outputLimitBytes:s,stdin:e.stdin??``,timeLimitSeconds:l}),m=(Date.now()-o)/1e3;return u(c?{elapsedTimeSeconds:m,options:e,result:{...p,timeSeconds:c.timeSeconds+p.timeSeconds,memoryBytes:Math.max(c.memoryBytes,p.memoryBytes)}}:{elapsedTimeSeconds:m,options:e,result:p})}finally{await t.forciblyRemoveDirectory(i)}}function u(e){return{stdin:e.options.stdin??``,stdout:e.result.stdout,stderr:e.result.stderr,status:e.result.timedOut||e.result.outputLimitExceeded?0:e.result.status,timeSeconds:e.result.timedOut?e.options.timeLimitSeconds+.001:e.result.timeSeconds||e.elapsedTimeSeconds,memoryBytes:e.result.memoryBytes,timedOut:e.result.timedOut,signal:e.result.signal,outputLimitExceeded:e.result.outputLimitExceeded}}function d(e,t){return s[e](t)}function f(e){return e.status!==0||e.timedOut||e.outputLimitExceeded}async function p(e){if(await T(n.default.join(e,`package.json`)))return await w(e,[`bun.lock`,`bun.lockb`])?[`bun`,`install`,`--frozen-lockfile`,`--silent`]:[`bun`,`install`,`--silent`]}async function m(e){if(await T(n.default.join(e,`Cargo.toml`)))return await T(n.default.join(e,`Cargo.lock`))?[`cargo`,`fetch`,`--locked`]:[`cargo`,`fetch`]}async function h(e){if(await T(n.default.join(e,`go.mod`)))return[`go`,`mod`,`download`]}async function g(e){if(!await w(e,[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradlew`,`gradlew.bat`]))return;let t=[`--no-daemon`,`--quiet`,`dependencies`];return process.platform===`win32`?await T(n.default.join(e,`gradlew.bat`))?[`cmd.exe`,`/c`,`gradlew.bat`,...t]:[`gradle`,...t]:await T(n.default.join(e,`gradlew`))?[`sh`,`./gradlew`,...t]:[`gradle`,...t]}async function _(e){if(!await T(n.default.join(e,`pom.xml`)))return;let t=[`-q`,`dependency:go-offline`];return process.platform===`win32`?await T(n.default.join(e,`mvnw.cmd`))?[`cmd.exe`,`/c`,`mvnw.cmd`,...t]:[`mvn`,...t]:await T(n.default.join(e,`mvnw`))?[`sh`,`./mvnw`,...t]:[`mvn`,...t]}async function v(e){if(await T(n.default.join(e,`package.json`)))return await T(n.default.join(e,`package-lock.json`))?[`npm`,`ci`,`--silent`]:[`npm`,`install`,`--silent`]}async function y(e){if(await T(n.default.join(e,`package.json`)))return await T(n.default.join(e,`pnpm-lock.yaml`))?[`pnpm`,`install`,`--frozen-lockfile`,`--silent`]:[`pnpm`,`install`,`--silent`]}async function b(e){if(await T(n.default.join(e,`Gemfile`)))return await T(n.default.join(e,`Gemfile.lock`))?[`bundle`,`install`,`--frozen`,`--quiet`]:[`bundle`,`install`,`--quiet`]}async function x(){}async function S(e){if(!await T(n.default.join(e,`package.json`)))return;let t=await C(e),r=await T(n.default.join(e,`yarn.lock`));return t?r?[`yarn`,`install`,`--immutable`]:[`yarn`,`install`]:r?[`yarn`,`install`,`--frozen-lockfile`,`--silent`]:[`yarn`,`install`,`--silent`]}async function C(e){if(await T(n.default.join(e,`.yarnrc.yml`)))return!0;let t=await E(n.default.join(e,`package.json`)),r=typeof t.packageManager==`string`?t.packageManager:void 0,i=/^yarn@(\d+)/.exec(r??``)?.[1];return i!==void 0&&Number(i)>=2}async function w(e,t){for(let r of t)if(await T(n.default.join(e,r)))return!0;return!1}async function T(e){try{return await r.default.access(e),!0}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e;return!1}}async function E(e){try{let t=JSON.parse(await r.default.readFile(e,`utf8`));return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch(e){if(e instanceof SyntaxError||(typeof e==`object`&&e&&`code`in e?e.code:void 0)===`ENOENT`)return{};throw e}}async function D(e){for(let t of e.projectFilePaths??o[e.packageManager])await O(n.default.join(e.projectDir,t),n.default.join(e.runDir,t))}async function O(e,t){try{await r.default.lstat(e),await r.default.mkdir(n.default.dirname(t),{recursive:!0}),await r.default.cp(e,t,{force:!0,recursive:!0})}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e}}async function k(e,t){let r=c===void 0?void 0:n.default.join(t.cwd,`.exercode-time-result`),a=c===void 0?e:[...c,`--output=${r}`,...e],o=i.default.spawn(a[0],a.slice(1),{cwd:t.cwd,detached:process.platform!==`win32`,env:t.env,stdio:[`pipe`,`pipe`,`pipe`]}),s=[],l=[],u=0,d=!1,f=!1,p=(e,n)=>{if(u>=t.outputLimitBytes){n.byteLength>0&&(f=!0,j(o,`SIGKILL`));return}let r=t.outputLimitBytes-u,i=n.byteLength>r?n.subarray(0,r):n;e.push(i),u+=i.byteLength,n.byteLength>r&&(f=!0,j(o,`SIGKILL`))};o.stdout.on(`data`,e=>p(s,e)),o.stderr.on(`data`,e=>p(l,e));let m=setTimeout(()=>{d=!0,j(o,`SIGTERM`)},t.timeLimitSeconds*1e3),h=setTimeout(()=>{d&&j(o,`SIGKILL`)},t.timeLimitSeconds*1e3+1e3);h.unref();let{status:g,signal:_}=await new Promise((e,n)=>{let r=!1,i,a=e=>{r||(i=e,j(o,`SIGKILL`),o.pid===void 0&&(r=!0,n(e)))};o.on(`error`,a),o.stdin.on(`error`,e=>{e.code!==`EPIPE`&&a(e)}),o.on(`close`,(t,a)=>{if(!r){if(r=!0,i){n(i);return}e({status:t??void 0,signal:a??void 0})}}),o.stdin.end(t.stdin)}).finally(()=>{clearTimeout(m),clearTimeout(h)}),{timeSeconds:v,memoryBytes:y}=r===void 0?{timeSeconds:0,memoryBytes:0}:await N(r);return{stdout:Buffer.concat(s).toString(),stderr:Buffer.concat(l).toString(),status:g,timeSeconds:v,memoryBytes:y,timedOut:d,signal:_,outputLimitExceeded:f}}function A(){let e=a.default.platform()===`darwin`?`gtime`:`/usr/bin/time`,t=i.default.spawnSync(e,[`--version`],{stdio:`ignore`});if(!(t.error||t.status!==0))return[e,`--format`,`%e %M`]}function j(e,t){if(e.pid!==void 0)try{if(process.platform===`win32`){e.kill(t);return}process.kill(-e.pid,t)}catch(e){let t=typeof e==`object`&&e&&`code`in e?e.code:void 0;if(t!==`ESRCH`&&t!==`EPERM`)throw e}}function M(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function N(e){let t;try{t=await r.default.readFile(e,`utf8`)}catch(e){if(M(e,`ENOENT`))return{timeSeconds:0,memoryBytes:0};throw e}let n=/(\d+(?:[.,]\d+)?) (\d+)\s*$/.exec(t);return n?{timeSeconds:Number(n[1].replace(`,`,`.`)),memoryBytes:Number(n[2])*1024}:{timeSeconds:0,memoryBytes:0}}exports.copyPackageManagerProjectFiles=D,exports.runCommandInTemporaryPackageManagerProject=l;
2
2
  //# sourceMappingURL=runCommandInTemporaryPackageManagerProject.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"runCommandInTemporaryPackageManagerProject.cjs","names":["fs","path","os","sandboxUserName","forceRemove","createDirectoryWithoutFollowingSymlinks","copyWithoutFollowingSymlinks","wrapCommandWithSandboxUser","prependInsideSandboxWrapper","startSandboxTimeoutWatchdog","childProcess","getSandboxUserEnvOverrides","nodeFs"],"sources":["../../src/helpers/runCommandInTemporaryPackageManagerProject.ts"],"sourcesContent":["import childProcess from 'node:child_process';\nimport nodeFs from 'node:fs';\nimport fs from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport {\n forceRemove,\n getSandboxUserEnvOverrides,\n killSandboxUserProcesses,\n makeAccessibleToSandboxUser,\n prependInsideSandboxWrapper,\n SANDBOX_WATCHDOG_GRACE_SECONDS,\n sandboxUserName,\n startSandboxTimeoutWatchdog,\n wrapCommandWithSandboxUser,\n} from './sandboxUser.js';\nimport { copyWithoutFollowingSymlinks, createDirectoryWithoutFollowingSymlinks } from './safeFs.js';\n\nexport type PackageManager = 'bun' | 'cargo' | 'go' | 'gradle' | 'maven' | 'npm' | 'pnpm' | 'ruby' | 'uv' | 'yarn';\ntype PackageManagerInstallCommand = readonly [string, ...string[]];\n\nexport interface PackageManagerCommandRunResult {\n stdin: string;\n stdout: string;\n stderr: string;\n status: number | undefined;\n timeSeconds: number;\n memoryBytes: number;\n timedOut: boolean;\n signal: NodeJS.Signals | undefined;\n outputLimitExceeded: boolean;\n}\n\nexport interface RunCommandInTemporaryPackageManagerProjectOptions {\n cwd: string;\n projectDir: string;\n packageManager: PackageManager;\n command: readonly [string, ...string[]] | ((context: { runDir: string }) => readonly [string, ...string[]]);\n /**\n * Set to false when `command` prepares the dependencies it needs.\n * Defaults to true.\n */\n prepareDependencies?: boolean;\n stdin?: string;\n env?: NodeJS.ProcessEnv;\n timeLimitSeconds: number;\n outputLimitBytes?: number;\n tempDirPrefix?: string;\n projectFilePaths?: readonly string[];\n}\n\nconst packageManagerProjectFilePaths = {\n bun: ['package.json', 'bun.lock', 'bun.lockb'],\n cargo: ['Cargo.toml', 'Cargo.lock'],\n go: ['go.mod', 'go.sum'],\n gradle: [\n 'build.gradle',\n 'build.gradle.kts',\n 'settings.gradle',\n 'settings.gradle.kts',\n 'gradle.properties',\n 'gradle.lockfile',\n 'buildscript-gradle.lockfile',\n 'gradle',\n 'gradlew',\n 'gradlew.bat',\n ],\n maven: ['pom.xml', '.mvn', 'mvnw', 'mvnw.cmd'],\n npm: ['package.json', 'package-lock.json'],\n pnpm: ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'],\n ruby: ['Gemfile', 'Gemfile.lock', '.ruby-version'],\n uv: ['pyproject.toml', 'uv.lock'],\n yarn: ['package.json', 'yarn.lock', '.yarnrc', '.yarnrc.yml', '.yarn'],\n} as const satisfies Record<PackageManager, readonly string[]>;\n\nconst packageManagerInstallCommandResolvers = {\n bun: resolveBunInstallCommand,\n cargo: resolveCargoInstallCommand,\n go: resolveGoInstallCommand,\n gradle: resolveGradleInstallCommand,\n maven: resolveMavenInstallCommand,\n npm: resolveNpmInstallCommand,\n pnpm: resolvePnpmInstallCommand,\n ruby: resolveRubyInstallCommand,\n uv: resolveUvInstallCommand,\n yarn: resolveYarnInstallCommand,\n} as const satisfies Record<PackageManager, (runDir: string) => Promise<PackageManagerInstallCommand | undefined>>;\n\nconst defaultOutputLimitBytes = 50 * 1024 * 1024;\nconst killGracePeriodMilliseconds = 1000;\n// Added to the watchdog's own deadline so its kill has time to land and `close` to arrive.\nconst watchdogSettleMarginMilliseconds = 2000;\nconst timeCommand = resolveTimeCommand();\n\n/**\n * Copies a submission directory to a temporary directory, overlays package\n * manager project files from the problem directory, prepares dependencies,\n * runs a command, and then removes the temporary directory.\n *\n * Under `EXERCODE_SANDBOX_USER` delegation, cleanup kills every process of the sandbox user, so do\n * not run multiple invocations concurrently in that mode — one finishing would kill the others.\n */\nexport async function runCommandInTemporaryPackageManagerProject(\n options: RunCommandInTemporaryPackageManagerProjectOptions\n): Promise<PackageManagerCommandRunResult> {\n const runDir = await fs.mkdtemp(path.join(os.tmpdir(), options.tempDirPrefix ?? 'exercode-'));\n try {\n await fs.cp(options.cwd, runDir, { recursive: true });\n await copyPackageManagerProjectFiles({\n packageManager: options.packageManager,\n projectDir: options.projectDir,\n runDir,\n projectFilePaths: options.projectFilePaths,\n });\n // The sandbox user (if any) runs the install/run commands below and must read the copied\n // sources and create outputs (e.g. `node_modules`, `.venv`) next to them.\n makeAccessibleToSandboxUser(runDir);\n\n const env = options.env ? { ...process.env, ...options.env } : process.env;\n const installCommand =\n options.prepareDependencies === false ? undefined : await resolveInstallCommand(options.packageManager, runDir);\n const command = typeof options.command === 'function' ? options.command({ runDir }) : options.command;\n const startedAt = Date.now();\n const outputLimitBytes = options.outputLimitBytes ?? defaultOutputLimitBytes;\n let installResult: Awaited<ReturnType<typeof spawnWithInput>> | undefined;\n\n if (installCommand) {\n installResult = await spawnWithInput(installCommand, {\n cwd: runDir,\n env,\n outputLimitBytes,\n stdin: '',\n timeLimitSeconds: options.timeLimitSeconds,\n });\n if (isFailedSpawnResult(installResult)) {\n return toPackageManagerCommandRunResult({\n elapsedTimeSeconds: (Date.now() - startedAt) / 1000,\n options,\n result: installResult,\n });\n }\n }\n\n const remainingTimeLimitSeconds = options.timeLimitSeconds - (Date.now() - startedAt) / 1000;\n if (remainingTimeLimitSeconds <= 0) {\n return {\n stdin: options.stdin ?? '',\n stdout: installResult?.stdout ?? '',\n stderr: installResult?.stderr ?? '',\n status: 0,\n timeSeconds: options.timeLimitSeconds + 1e-3,\n memoryBytes: installResult?.memoryBytes ?? 0,\n timedOut: true,\n signal: installResult?.signal,\n outputLimitExceeded: false,\n };\n }\n\n const result = await spawnWithInput(command, {\n cwd: runDir,\n env,\n outputLimitBytes,\n stdin: options.stdin ?? '',\n timeLimitSeconds: remainingTimeLimitSeconds,\n });\n const elapsedTimeSeconds = (Date.now() - startedAt) / 1000;\n\n if (installResult) {\n return toPackageManagerCommandRunResult({\n elapsedTimeSeconds,\n options,\n result: {\n ...result,\n timeSeconds: installResult.timeSeconds + result.timeSeconds,\n memoryBytes: Math.max(installResult.memoryBytes, result.memoryBytes),\n },\n });\n }\n\n return toPackageManagerCommandRunResult({ elapsedTimeSeconds, options, result });\n } finally {\n try {\n // Daemonized children of the sandboxed command would otherwise outlive the run.\n if (sandboxUserName) killSandboxUserProcesses();\n } finally {\n // Must run even when the sweep fails closed, or the temporary submission copy leaks.\n await forceRemove(runDir);\n }\n }\n}\n\nfunction toPackageManagerCommandRunResult(context: {\n elapsedTimeSeconds: number;\n options: RunCommandInTemporaryPackageManagerProjectOptions;\n result: Awaited<ReturnType<typeof spawnWithInput>>;\n}): PackageManagerCommandRunResult {\n return {\n stdin: context.options.stdin ?? '',\n stdout: context.result.stdout,\n stderr: context.result.stderr,\n status: context.result.timedOut || context.result.outputLimitExceeded ? 0 : context.result.status,\n timeSeconds: context.result.timedOut\n ? context.options.timeLimitSeconds + 1e-3\n : context.result.timeSeconds || context.elapsedTimeSeconds,\n memoryBytes: context.result.memoryBytes,\n timedOut: context.result.timedOut,\n signal: context.result.signal,\n outputLimitExceeded: context.result.outputLimitExceeded,\n };\n}\n\nfunction resolveInstallCommand(\n packageManager: PackageManager,\n runDir: string\n): Promise<PackageManagerInstallCommand | undefined> {\n return packageManagerInstallCommandResolvers[packageManager](runDir);\n}\n\nfunction isFailedSpawnResult(result: Awaited<ReturnType<typeof spawnWithInput>>): boolean {\n return result.status !== 0 || result.timedOut || result.outputLimitExceeded;\n}\n\nasync function resolveBunInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n // Bun supports --silent and it keeps successful preparation output out of judge output buffers.\n return (await hasAnyPath(runDir, ['bun.lock', 'bun.lockb']))\n ? ['bun', 'install', '--frozen-lockfile', '--silent']\n : ['bun', 'install', '--silent'];\n}\n\nasync function resolveCargoInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'Cargo.toml')))) return undefined;\n return (await pathExists(path.join(runDir, 'Cargo.lock'))) ? ['cargo', 'fetch', '--locked'] : ['cargo', 'fetch'];\n}\n\nasync function resolveGoInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'go.mod')))) return undefined;\n return ['go', 'mod', 'download'];\n}\n\nasync function resolveGradleInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (\n !(await hasAnyPath(runDir, [\n 'build.gradle',\n 'build.gradle.kts',\n 'settings.gradle',\n 'settings.gradle.kts',\n 'gradlew',\n 'gradlew.bat',\n ]))\n )\n return undefined;\n const args = ['--no-daemon', '--quiet', 'dependencies'] as const;\n if (process.platform === 'win32') {\n return (await pathExists(path.join(runDir, 'gradlew.bat')))\n ? ['cmd.exe', '/c', 'gradlew.bat', ...args]\n : ['gradle', ...args];\n }\n return (await pathExists(path.join(runDir, 'gradlew'))) ? ['sh', './gradlew', ...args] : ['gradle', ...args];\n}\n\nasync function resolveMavenInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'pom.xml')))) return undefined;\n const args = ['-q', 'dependency:go-offline'] as const;\n if (process.platform === 'win32') {\n return (await pathExists(path.join(runDir, 'mvnw.cmd')))\n ? ['cmd.exe', '/c', 'mvnw.cmd', ...args]\n : ['mvn', ...args];\n }\n return (await pathExists(path.join(runDir, 'mvnw'))) ? ['sh', './mvnw', ...args] : ['mvn', ...args];\n}\n\nasync function resolveNpmInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n return (await pathExists(path.join(runDir, 'package-lock.json')))\n ? ['npm', 'ci', '--silent']\n : ['npm', 'install', '--silent'];\n}\n\nasync function resolvePnpmInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n return (await pathExists(path.join(runDir, 'pnpm-lock.yaml')))\n ? ['pnpm', 'install', '--frozen-lockfile', '--silent']\n : ['pnpm', 'install', '--silent'];\n}\n\nasync function resolveRubyInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'Gemfile')))) return undefined;\n return (await pathExists(path.join(runDir, 'Gemfile.lock')))\n ? ['bundle', 'install', '--frozen', '--quiet']\n : ['bundle', 'install', '--quiet'];\n}\n\nasync function resolveUvInstallCommand(): Promise<undefined> {\n return undefined;\n}\n\nasync function resolveYarnInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n const isBerry = await isYarnBerryProject(runDir);\n const hasLockfile = await pathExists(path.join(runDir, 'yarn.lock'));\n if (isBerry) return hasLockfile ? ['yarn', 'install', '--immutable'] : ['yarn', 'install'];\n return hasLockfile ? ['yarn', 'install', '--frozen-lockfile', '--silent'] : ['yarn', 'install', '--silent'];\n}\n\nasync function isYarnBerryProject(runDir: string): Promise<boolean> {\n if (await pathExists(path.join(runDir, '.yarnrc.yml'))) return true;\n\n const packageJson = await readJson(path.join(runDir, 'package.json'));\n const packageManager = typeof packageJson.packageManager === 'string' ? packageJson.packageManager : undefined;\n const yarnMajorVersion = /^yarn@(\\d+)/.exec(packageManager ?? '')?.[1];\n return yarnMajorVersion !== undefined && Number(yarnMajorVersion) >= 2;\n}\n\nasync function hasAnyPath(directoryPath: string, relativePaths: readonly string[]): Promise<boolean> {\n for (const relativePath of relativePaths) {\n if (await pathExists(path.join(directoryPath, relativePath))) return true;\n }\n return false;\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch (error) {\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code !== 'ENOENT') throw error;\n return false;\n }\n}\n\nasync function readJson(filePath: string): Promise<Record<string, unknown>> {\n try {\n const parsed = JSON.parse(await fs.readFile(filePath, 'utf8')) as unknown;\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch (error) {\n if (error instanceof SyntaxError) return {};\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code === 'ENOENT') return {};\n throw error;\n }\n}\n\nexport async function copyPackageManagerProjectFiles(options: {\n packageManager: PackageManager;\n projectDir: string;\n runDir: string;\n projectFilePaths?: readonly string[];\n}): Promise<void> {\n for (const projectFilePath of options.projectFilePaths ?? packageManagerProjectFilePaths[options.packageManager]) {\n await copyPathIfExists(\n path.join(options.projectDir, projectFilePath),\n path.join(options.runDir, projectFilePath),\n options.runDir\n );\n }\n}\n\nasync function copyPathIfExists(sourcePath: string, destinationPath: string, runDir: string): Promise<void> {\n try {\n // Before touching the destination: creating the parent levels replaces whatever the submission\n // put there, which must not happen for a project file the problem does not even ship.\n await fs.lstat(sourcePath);\n // No-follow copy: the destination was seeded from the (sandbox-writable) submission tree, so a\n // planted symlink there — at the destination itself or at any directory level of a nested\n // project file path — must not redirect this trusted project-file overlay outside runDir.\n await createDirectoryWithoutFollowingSymlinks(runDir, path.dirname(destinationPath));\n await copyWithoutFollowingSymlinks(sourcePath, destinationPath);\n } catch (error) {\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code !== 'ENOENT') throw error;\n }\n}\n\nasync function spawnWithInput(\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<{\n stdout: string;\n stderr: string;\n status: number | undefined;\n timeSeconds: number;\n memoryBytes: number;\n timedOut: boolean;\n signal: NodeJS.Signals | undefined;\n outputLimitExceeded: boolean;\n}> {\n const timeOutputPath = timeCommand === undefined ? undefined : path.join(context.cwd, '.exercode-time-result');\n // `wrapCommandWithSandboxUser` is idempotent, so a command the presets already wrapped is not\n // nested; `time` is then spliced INSIDE that wrapper so it runs as the sandbox user, never as the\n // harness user writing `--output` into this sandbox-writable directory.\n const wrappedCommand = wrapCommandWithSandboxUser(command);\n const spawnedCommand =\n timeCommand === undefined\n ? wrappedCommand\n : prependInsideSandboxWrapper(wrappedCommand, [...timeCommand, `--output=${timeOutputPath}`]);\n // Started BEFORE the submission: `killSubprocessGroup` cannot spawn its `sudo` once a submission\n // has exhausted the PID cgroup, and a submission spawned first could exhaust it before this\n // watchdog exists. It is the deadline of last resort on this path.\n const watchdog = startSandboxTimeoutWatchdog(context.timeLimitSeconds);\n const watchdogDeadlineAt = Date.now() + (Math.ceil(context.timeLimitSeconds) + SANDBOX_WATCHDOG_GRACE_SECONDS) * 1000;\n let subprocess: childProcess.ChildProcessWithoutNullStreams;\n try {\n subprocess = childProcess.spawn(spawnedCommand[0], spawnedCommand.slice(1), {\n cwd: context.cwd,\n detached: process.platform !== 'win32',\n env: { ...context.env, ...getSandboxUserEnvOverrides(context.env) },\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n } catch (error) {\n watchdog.cancel();\n throw error;\n }\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let outputBytes = 0;\n let timedOut = false;\n let outputLimitExceeded = false;\n // Set when terminating the submission failed (the cleanup `sudo` could not be spawned). The run\n // then waits for the watchdog to end the submission rather than throwing out of an EventEmitter\n // callback, which would be an uncaught exception that kills the harness before any cleanup.\n let killError: Error | undefined;\n let onKillFailure: (() => void) | undefined;\n const killOrRecordFailure = (signal: NodeJS.Signals): void => {\n try {\n killSubprocessGroup(subprocess, signal);\n } catch (error) {\n killError ??= error instanceof Error ? error : new Error(String(error));\n onKillFailure?.();\n }\n };\n\n const appendOutputChunk = (chunks: Buffer[], chunk: Buffer): void => {\n if (outputBytes >= context.outputLimitBytes) {\n if (chunk.byteLength > 0) {\n outputLimitExceeded = true;\n killOrRecordFailure('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 killOrRecordFailure('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 killOrRecordFailure('SIGTERM');\n }, context.timeLimitSeconds * 1000);\n const killTimeout = setTimeout(\n () => {\n if (timedOut) killOrRecordFailure('SIGKILL');\n },\n context.timeLimitSeconds * 1000 + killGracePeriodMilliseconds\n );\n killTimeout.unref();\n // Bounds the wait after a kill failure: the watchdog force-kills the sandbox user at its own\n // deadline, so `close` should arrive; if even that fails, give up rather than hang.\n let killFailureTimeout: ReturnType<typeof setTimeout> | undefined;\n let closeObserved = false;\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 const failAfterClose = (error: Error): void => {\n if (settled) return;\n pendingError = error;\n killOrRecordFailure('SIGKILL');\n if (subprocess.pid === undefined) {\n settled = true;\n reject(error);\n }\n };\n // Terminating the submission failed. Keep waiting: the watchdog (started before the\n // submission) force-kills the sandbox user at its own deadline, so `close` still arrives and\n // the run reports its real verdict. Give up only once that deadline has passed without the\n // submission ending, so the run can neither hang nor abandon a still-running submission\n // while its watchdog could still fire.\n onKillFailure = () => {\n killFailureTimeout ??= setTimeout(\n () => {\n if (settled) return;\n settled = true;\n reject(killError ?? new Error('failed to terminate the submission'));\n },\n Math.max(0, watchdogDeadlineAt - Date.now()) + watchdogSettleMarginMilliseconds\n );\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('close', (code, closeSignal) => {\n if (settled) return;\n settled = true;\n // The submission ended, so the watchdog has nothing left to kill and must not outlive this\n // run. A kill that failed once but succeeded on retry (or was superseded by the watchdog)\n // is not an error: the timeout/output-limit verdict below is the correct one to report.\n closeObserved = true;\n if (pendingError) {\n reject(pendingError);\n return;\n }\n resolve({ status: code ?? undefined, signal: closeSignal ?? undefined });\n });\n subprocess.stdin.end(context.stdin);\n }\n ).finally(() => {\n clearTimeout(timeout);\n clearTimeout(killTimeout);\n if (killFailureTimeout) clearTimeout(killFailureTimeout);\n // Cancel unless the submission is still running after a failed kill: the watchdog is then the\n // only remaining mechanism able to stop it, and cancelling would leave it running unchecked.\n if (closeObserved || !killError) watchdog.cancel();\n });\n\n const { timeSeconds, memoryBytes } =\n timeOutputPath === undefined ? { timeSeconds: 0, memoryBytes: 0 } : await readTimeResult(timeOutputPath);\n\n return {\n stdout: Buffer.concat(stdoutChunks).toString(),\n stderr: Buffer.concat(stderrChunks).toString(),\n status,\n timeSeconds,\n memoryBytes,\n timedOut,\n signal,\n outputLimitExceeded,\n };\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 return [command, '--format', '%e %M'];\n}\n\nfunction killSubprocessGroup(subprocess: childProcess.ChildProcess, signal: NodeJS.Signals): void {\n if (subprocess.pid === undefined) return;\n\n // The current user cannot signal the root-owned sudo wrapper nor the sandbox user's processes,\n // so go through sudo with the requested signal only; the callers' existing timers provide the\n // TERM → grace → KILL escalation.\n // Throws when the cleanup `sudo` cannot even be spawned (a submission can exhaust the PID\n // cgroup). Only `killOrRecordFailure` may call this: it records the failure and lets the\n // watchdog (or, past its deadline, a bounded timer) settle the run instead of letting the throw\n // escape an EventEmitter callback.\n if (sandboxUserName) {\n killSandboxUserProcesses([signal === 'SIGKILL' ? 'KILL' : 'TERM']);\n return;\n }\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 const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code !== 'ESRCH' && code !== 'EPERM') throw error;\n }\n}\n\nfunction isErrorWithCode(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && (error as { code: unknown }).code === code;\n}\n\nasync function readTimeResult(timeOutputPath: string): Promise<{ timeSeconds: number; memoryBytes: number }> {\n // The submission owns this directory and can put anything at this path, so decide what was\n // opened from the handle itself rather than from a prior `lstat` it could race:\n // - `O_NOFOLLOW` refuses a symlink to a harness-readable file (e.g. the problem's expected\n // outputs), which would otherwise report that file's trailing numbers as the submission's own\n // time and memory usage;\n // - `O_NONBLOCK` keeps a planted FIFO from blocking the harness forever waiting for a writer;\n // - the `fstat` then rejects anything that is not a regular file.\n //\n // Only an absent file means \"no measurement\" (the command was killed before `time` wrote one).\n // Anything else at this path is the submission tampering with its own accounting — reporting zero\n // memory would let it slip past a memory limit — so that fails the run instead.\n let content: string;\n let fileHandle: Awaited<ReturnType<typeof fs.open>> | undefined;\n try {\n fileHandle = await fs.open(\n timeOutputPath,\n nodeFs.constants.O_RDONLY | nodeFs.constants.O_NOFOLLOW | nodeFs.constants.O_NONBLOCK\n );\n const stats = await fileHandle.stat();\n if (!stats.isFile()) throw new Error(`${timeOutputPath} is not a regular file`);\n content = await fileHandle.readFile('utf8');\n } catch (error) {\n if (isErrorWithCode(error, 'ENOENT')) return { timeSeconds: 0, memoryBytes: 0 };\n throw new Error(`failed to read the time measurement at ${timeOutputPath}`, { cause: error });\n } finally {\n await fileHandle?.close();\n }\n\n const match = /(\\d+(?:[.,]\\d+)?) (\\d+)\\s*$/.exec(content);\n if (!match) return { timeSeconds: 0, memoryBytes: 0 };\n\n return { timeSeconds: Number(match[1]!.replace(',', '.')), memoryBytes: Number(match[2]) * 1024 };\n}\n"],"mappings":"mWAoDA,MAAM,EAAiC,CACrC,IAAK,CAAC,eAAgB,WAAY,WAAW,EAC7C,MAAO,CAAC,aAAc,YAAY,EAClC,GAAI,CAAC,SAAU,QAAQ,EACvB,OAAQ,CACN,eACA,mBACA,kBACA,sBACA,oBACA,kBACA,8BACA,SACA,UACA,aACF,EACA,MAAO,CAAC,UAAW,OAAQ,OAAQ,UAAU,EAC7C,IAAK,CAAC,eAAgB,mBAAmB,EACzC,KAAM,CAAC,eAAgB,iBAAkB,qBAAqB,EAC9D,KAAM,CAAC,UAAW,eAAgB,eAAe,EACjD,GAAI,CAAC,iBAAkB,SAAS,EAChC,KAAM,CAAC,eAAgB,YAAa,UAAW,cAAe,OAAO,CAC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AAS,CACjH,CAEA,eAAe,EAAe,EAA+E,CAY3G,IAAI,EACA,EACJ,GAAI,CAMF,GALA,EAAa,MAAMH,EAAAA,QAAG,KACpB,EACAY,EAAAA,QAAO,UAAU,SAAWA,EAAAA,QAAO,UAAU,WAAaA,EAAAA,QAAO,UAAU,UAC7E,EAEI,EAAC,MADe,EAAW,KAAK,EAAA,CACzB,OAAO,EAAG,MAAU,MAAM,GAAG,EAAe,uBAAuB,EAC9E,EAAU,MAAM,EAAW,SAAS,MAAM,CAC5C,OAAS,EAAO,CACd,GAAI,EAAgB,EAAO,QAAQ,EAAG,MAAO,CAAE,YAAa,EAAG,YAAa,CAAE,EAC9E,MAAU,MAAM,0CAA0C,IAAkB,CAAE,MAAO,CAAM,CAAC,CAC9F,QAAU,CACR,MAAM,GAAY,MAAM,CAC1B,CAEA,IAAM,EAAQ,8BAA8B,KAAK,CAAO,EAGxD,OAFK,EAEE,CAAE,YAAa,OAAO,EAAM,EAAE,CAAE,QAAQ,IAAK,GAAG,CAAC,EAAG,YAAa,OAAO,EAAM,EAAE,EAAI,IAAK,EAF7E,CAAE,YAAa,EAAG,YAAa,CAAE,CAGtD"}
1
+ {"version":3,"file":"runCommandInTemporaryPackageManagerProject.cjs","names":["fs","path","os","forciblyRemoveDirectory","childProcess"],"sources":["../../src/helpers/runCommandInTemporaryPackageManagerProject.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 { forciblyRemoveDirectory } from './temporaryProblemDirCopy.js';\n\nexport type PackageManager = 'bun' | 'cargo' | 'go' | 'gradle' | 'maven' | 'npm' | 'pnpm' | 'ruby' | 'uv' | 'yarn';\ntype PackageManagerInstallCommand = readonly [string, ...string[]];\n\nexport interface PackageManagerCommandRunResult {\n stdin: string;\n stdout: string;\n stderr: string;\n status: number | undefined;\n timeSeconds: number;\n memoryBytes: number;\n timedOut: boolean;\n signal: NodeJS.Signals | undefined;\n outputLimitExceeded: boolean;\n}\n\nexport interface RunCommandInTemporaryPackageManagerProjectOptions {\n cwd: string;\n projectDir: string;\n packageManager: PackageManager;\n command: readonly [string, ...string[]] | ((context: { runDir: string }) => readonly [string, ...string[]]);\n /**\n * Set to false when `command` prepares the dependencies it needs.\n * Defaults to true.\n */\n prepareDependencies?: boolean;\n stdin?: string;\n env?: NodeJS.ProcessEnv;\n timeLimitSeconds: number;\n outputLimitBytes?: number;\n tempDirPrefix?: string;\n projectFilePaths?: readonly string[];\n}\n\nconst packageManagerProjectFilePaths = {\n bun: ['package.json', 'bun.lock', 'bun.lockb'],\n cargo: ['Cargo.toml', 'Cargo.lock'],\n go: ['go.mod', 'go.sum'],\n gradle: [\n 'build.gradle',\n 'build.gradle.kts',\n 'settings.gradle',\n 'settings.gradle.kts',\n 'gradle.properties',\n 'gradle.lockfile',\n 'buildscript-gradle.lockfile',\n 'gradle',\n 'gradlew',\n 'gradlew.bat',\n ],\n maven: ['pom.xml', '.mvn', 'mvnw', 'mvnw.cmd'],\n npm: ['package.json', 'package-lock.json'],\n pnpm: ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'],\n ruby: ['Gemfile', 'Gemfile.lock', '.ruby-version'],\n uv: ['pyproject.toml', 'uv.lock'],\n yarn: ['package.json', 'yarn.lock', '.yarnrc', '.yarnrc.yml', '.yarn'],\n} as const satisfies Record<PackageManager, readonly string[]>;\n\nconst packageManagerInstallCommandResolvers = {\n bun: resolveBunInstallCommand,\n cargo: resolveCargoInstallCommand,\n go: resolveGoInstallCommand,\n gradle: resolveGradleInstallCommand,\n maven: resolveMavenInstallCommand,\n npm: resolveNpmInstallCommand,\n pnpm: resolvePnpmInstallCommand,\n ruby: resolveRubyInstallCommand,\n uv: resolveUvInstallCommand,\n yarn: resolveYarnInstallCommand,\n} as const satisfies Record<PackageManager, (runDir: string) => Promise<PackageManagerInstallCommand | undefined>>;\n\nconst defaultOutputLimitBytes = 50 * 1024 * 1024;\nconst killGracePeriodMilliseconds = 1000;\nconst timeCommand = resolveTimeCommand();\n\n/**\n * Copies a submission directory to a temporary directory, overlays package\n * manager project files from the problem directory, prepares dependencies,\n * runs a command, and then removes the temporary directory.\n */\nexport async function runCommandInTemporaryPackageManagerProject(\n options: RunCommandInTemporaryPackageManagerProjectOptions\n): Promise<PackageManagerCommandRunResult> {\n const runDir = await fs.mkdtemp(path.join(os.tmpdir(), options.tempDirPrefix ?? 'exercode-'));\n try {\n await fs.cp(options.cwd, runDir, { recursive: true });\n await copyPackageManagerProjectFiles({\n packageManager: options.packageManager,\n projectDir: options.projectDir,\n runDir,\n projectFilePaths: options.projectFilePaths,\n });\n\n const env = options.env ? { ...process.env, ...options.env } : process.env;\n const installCommand =\n options.prepareDependencies === false ? undefined : await resolveInstallCommand(options.packageManager, runDir);\n const command = typeof options.command === 'function' ? options.command({ runDir }) : options.command;\n const startedAt = Date.now();\n const outputLimitBytes = options.outputLimitBytes ?? defaultOutputLimitBytes;\n let installResult: Awaited<ReturnType<typeof spawnWithInput>> | undefined;\n\n if (installCommand) {\n installResult = await spawnWithInput(installCommand, {\n cwd: runDir,\n env,\n outputLimitBytes,\n stdin: '',\n timeLimitSeconds: options.timeLimitSeconds,\n });\n if (isFailedSpawnResult(installResult)) {\n return toPackageManagerCommandRunResult({\n elapsedTimeSeconds: (Date.now() - startedAt) / 1000,\n options,\n result: installResult,\n });\n }\n }\n\n const remainingTimeLimitSeconds = options.timeLimitSeconds - (Date.now() - startedAt) / 1000;\n if (remainingTimeLimitSeconds <= 0) {\n return {\n stdin: options.stdin ?? '',\n stdout: installResult?.stdout ?? '',\n stderr: installResult?.stderr ?? '',\n status: 0,\n timeSeconds: options.timeLimitSeconds + 1e-3,\n memoryBytes: installResult?.memoryBytes ?? 0,\n timedOut: true,\n signal: installResult?.signal,\n outputLimitExceeded: false,\n };\n }\n\n const result = await spawnWithInput(command, {\n cwd: runDir,\n env,\n outputLimitBytes,\n stdin: options.stdin ?? '',\n timeLimitSeconds: remainingTimeLimitSeconds,\n });\n const elapsedTimeSeconds = (Date.now() - startedAt) / 1000;\n\n if (installResult) {\n return toPackageManagerCommandRunResult({\n elapsedTimeSeconds,\n options,\n result: {\n ...result,\n timeSeconds: installResult.timeSeconds + result.timeSeconds,\n memoryBytes: Math.max(installResult.memoryBytes, result.memoryBytes),\n },\n });\n }\n\n return toPackageManagerCommandRunResult({ elapsedTimeSeconds, options, result });\n } finally {\n // The command may have left permission-locked entries (e.g. a mode-000 directory).\n await forciblyRemoveDirectory(runDir);\n }\n}\n\nfunction toPackageManagerCommandRunResult(context: {\n elapsedTimeSeconds: number;\n options: RunCommandInTemporaryPackageManagerProjectOptions;\n result: Awaited<ReturnType<typeof spawnWithInput>>;\n}): PackageManagerCommandRunResult {\n return {\n stdin: context.options.stdin ?? '',\n stdout: context.result.stdout,\n stderr: context.result.stderr,\n status: context.result.timedOut || context.result.outputLimitExceeded ? 0 : context.result.status,\n timeSeconds: context.result.timedOut\n ? context.options.timeLimitSeconds + 1e-3\n : context.result.timeSeconds || context.elapsedTimeSeconds,\n memoryBytes: context.result.memoryBytes,\n timedOut: context.result.timedOut,\n signal: context.result.signal,\n outputLimitExceeded: context.result.outputLimitExceeded,\n };\n}\n\nfunction resolveInstallCommand(\n packageManager: PackageManager,\n runDir: string\n): Promise<PackageManagerInstallCommand | undefined> {\n return packageManagerInstallCommandResolvers[packageManager](runDir);\n}\n\nfunction isFailedSpawnResult(result: Awaited<ReturnType<typeof spawnWithInput>>): boolean {\n return result.status !== 0 || result.timedOut || result.outputLimitExceeded;\n}\n\nasync function resolveBunInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n // Bun supports --silent and it keeps successful preparation output out of judge output buffers.\n return (await hasAnyPath(runDir, ['bun.lock', 'bun.lockb']))\n ? ['bun', 'install', '--frozen-lockfile', '--silent']\n : ['bun', 'install', '--silent'];\n}\n\nasync function resolveCargoInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'Cargo.toml')))) return undefined;\n return (await pathExists(path.join(runDir, 'Cargo.lock'))) ? ['cargo', 'fetch', '--locked'] : ['cargo', 'fetch'];\n}\n\nasync function resolveGoInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'go.mod')))) return undefined;\n return ['go', 'mod', 'download'];\n}\n\nasync function resolveGradleInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (\n !(await hasAnyPath(runDir, [\n 'build.gradle',\n 'build.gradle.kts',\n 'settings.gradle',\n 'settings.gradle.kts',\n 'gradlew',\n 'gradlew.bat',\n ]))\n )\n return undefined;\n const args = ['--no-daemon', '--quiet', 'dependencies'] as const;\n if (process.platform === 'win32') {\n return (await pathExists(path.join(runDir, 'gradlew.bat')))\n ? ['cmd.exe', '/c', 'gradlew.bat', ...args]\n : ['gradle', ...args];\n }\n return (await pathExists(path.join(runDir, 'gradlew'))) ? ['sh', './gradlew', ...args] : ['gradle', ...args];\n}\n\nasync function resolveMavenInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'pom.xml')))) return undefined;\n const args = ['-q', 'dependency:go-offline'] as const;\n if (process.platform === 'win32') {\n return (await pathExists(path.join(runDir, 'mvnw.cmd')))\n ? ['cmd.exe', '/c', 'mvnw.cmd', ...args]\n : ['mvn', ...args];\n }\n return (await pathExists(path.join(runDir, 'mvnw'))) ? ['sh', './mvnw', ...args] : ['mvn', ...args];\n}\n\nasync function resolveNpmInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n return (await pathExists(path.join(runDir, 'package-lock.json')))\n ? ['npm', 'ci', '--silent']\n : ['npm', 'install', '--silent'];\n}\n\nasync function resolvePnpmInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n return (await pathExists(path.join(runDir, 'pnpm-lock.yaml')))\n ? ['pnpm', 'install', '--frozen-lockfile', '--silent']\n : ['pnpm', 'install', '--silent'];\n}\n\nasync function resolveRubyInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'Gemfile')))) return undefined;\n return (await pathExists(path.join(runDir, 'Gemfile.lock')))\n ? ['bundle', 'install', '--frozen', '--quiet']\n : ['bundle', 'install', '--quiet'];\n}\n\nasync function resolveUvInstallCommand(): Promise<undefined> {\n return undefined;\n}\n\nasync function resolveYarnInstallCommand(runDir: string): Promise<PackageManagerInstallCommand | undefined> {\n if (!(await pathExists(path.join(runDir, 'package.json')))) return undefined;\n const isBerry = await isYarnBerryProject(runDir);\n const hasLockfile = await pathExists(path.join(runDir, 'yarn.lock'));\n if (isBerry) return hasLockfile ? ['yarn', 'install', '--immutable'] : ['yarn', 'install'];\n return hasLockfile ? ['yarn', 'install', '--frozen-lockfile', '--silent'] : ['yarn', 'install', '--silent'];\n}\n\nasync function isYarnBerryProject(runDir: string): Promise<boolean> {\n if (await pathExists(path.join(runDir, '.yarnrc.yml'))) return true;\n\n const packageJson = await readJson(path.join(runDir, 'package.json'));\n const packageManager = typeof packageJson.packageManager === 'string' ? packageJson.packageManager : undefined;\n const yarnMajorVersion = /^yarn@(\\d+)/.exec(packageManager ?? '')?.[1];\n return yarnMajorVersion !== undefined && Number(yarnMajorVersion) >= 2;\n}\n\nasync function hasAnyPath(directoryPath: string, relativePaths: readonly string[]): Promise<boolean> {\n for (const relativePath of relativePaths) {\n if (await pathExists(path.join(directoryPath, relativePath))) return true;\n }\n return false;\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath);\n return true;\n } catch (error) {\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code !== 'ENOENT') throw error;\n return false;\n }\n}\n\nasync function readJson(filePath: string): Promise<Record<string, unknown>> {\n try {\n const parsed = JSON.parse(await fs.readFile(filePath, 'utf8')) as unknown;\n return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch (error) {\n if (error instanceof SyntaxError) return {};\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code === 'ENOENT') return {};\n throw error;\n }\n}\n\nexport async function copyPackageManagerProjectFiles(options: {\n packageManager: PackageManager;\n projectDir: string;\n runDir: string;\n projectFilePaths?: readonly string[];\n}): Promise<void> {\n for (const projectFilePath of options.projectFilePaths ?? packageManagerProjectFilePaths[options.packageManager]) {\n await copyPathIfExists(path.join(options.projectDir, projectFilePath), path.join(options.runDir, projectFilePath));\n }\n}\n\nasync function copyPathIfExists(sourcePath: string, destinationPath: string): Promise<void> {\n try {\n // Before touching the destination: creating the parent levels must not happen for a project\n // file the problem does not even ship.\n await fs.lstat(sourcePath);\n await fs.mkdir(path.dirname(destinationPath), { recursive: true });\n await fs.cp(sourcePath, destinationPath, { force: true, recursive: true });\n } catch (error) {\n const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code !== 'ENOENT') throw error;\n }\n}\n\nasync function spawnWithInput(\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<{\n stdout: string;\n stderr: string;\n status: number | undefined;\n timeSeconds: number;\n memoryBytes: number;\n timedOut: boolean;\n signal: NodeJS.Signals | undefined;\n outputLimitExceeded: boolean;\n}> {\n const timeOutputPath = timeCommand === undefined ? undefined : path.join(context.cwd, '.exercode-time-result');\n const spawnedCommand: readonly [string, ...string[]] =\n timeCommand === undefined ? command : [...timeCommand, `--output=${timeOutputPath}`, ...command];\n const subprocess = childProcess.spawn(spawnedCommand[0], spawnedCommand.slice(1), {\n cwd: context.cwd,\n detached: process.platform !== 'win32',\n env: context.env,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n const stdoutChunks: Buffer[] = [];\n const stderrChunks: Buffer[] = [];\n let outputBytes = 0;\n let timedOut = false;\n let outputLimitExceeded = false;\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 }, context.timeLimitSeconds * 1000);\n const killTimeout = setTimeout(\n () => {\n if (timedOut) killSubprocessGroup(subprocess, 'SIGKILL');\n },\n context.timeLimitSeconds * 1000 + killGracePeriodMilliseconds\n );\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 const failAfterClose = (error: Error): void => {\n if (settled) return;\n pendingError = error;\n killSubprocessGroup(subprocess, 'SIGKILL');\n if (subprocess.pid === undefined) {\n settled = true;\n reject(error);\n }\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('close', (code, closeSignal) => {\n if (settled) return;\n settled = true;\n if (pendingError) {\n reject(pendingError);\n return;\n }\n resolve({ status: code ?? undefined, signal: closeSignal ?? undefined });\n });\n subprocess.stdin.end(context.stdin);\n }\n ).finally(() => {\n clearTimeout(timeout);\n clearTimeout(killTimeout);\n });\n\n const { timeSeconds, memoryBytes } =\n timeOutputPath === undefined ? { timeSeconds: 0, memoryBytes: 0 } : await readTimeResult(timeOutputPath);\n\n return {\n stdout: Buffer.concat(stdoutChunks).toString(),\n stderr: Buffer.concat(stderrChunks).toString(),\n status,\n timeSeconds,\n memoryBytes,\n timedOut,\n signal,\n outputLimitExceeded,\n };\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 return [command, '--format', '%e %M'];\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 const code =\n typeof error === 'object' && error !== null && 'code' in error ? (error as { code: unknown }).code : undefined;\n if (code !== 'ESRCH' && code !== 'EPERM') throw error;\n }\n}\n\nfunction isErrorWithCode(error: unknown, code: string): boolean {\n return typeof error === 'object' && error !== null && 'code' in error && (error as { code: unknown }).code === code;\n}\n\nasync function readTimeResult(timeOutputPath: string): Promise<{ timeSeconds: number; memoryBytes: number }> {\n // An absent file means \"no measurement\" (the command was killed before `time` wrote one). Anything\n // else is read as-is: the submission shares this process's OS user, so a symlink or FIFO planted\n // here only affects its own run, which the judge server's request timeout ends.\n let content: string;\n try {\n content = await fs.readFile(timeOutputPath, 'utf8');\n } catch (error) {\n if (isErrorWithCode(error, 'ENOENT')) return { timeSeconds: 0, memoryBytes: 0 };\n throw error;\n }\n\n const match = /(\\d+(?:[.,]\\d+)?) (\\d+)\\s*$/.exec(content);\n if (!match) return {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E,CAAE,QAAQ,IAAK,GAAG,CAAC,EAAG,YAAa,OAAO,EAAM,EAAE,EAAI,IAAK,EAF7E,CAAE,YAAa,EAAG,YAAa,CAAE,CAGtD"}
@@ -33,9 +33,6 @@ export interface RunCommandInTemporaryPackageManagerProjectOptions {
33
33
  * Copies a submission directory to a temporary directory, overlays package
34
34
  * manager project files from the problem directory, prepares dependencies,
35
35
  * runs a command, and then removes the temporary directory.
36
- *
37
- * Under `EXERCODE_SANDBOX_USER` delegation, cleanup kills every process of the sandbox user, so do
38
- * not run multiple invocations concurrently in that mode — one finishing would kill the others.
39
36
  */
40
37
  export declare function runCommandInTemporaryPackageManagerProject(options: RunCommandInTemporaryPackageManagerProjectOptions): Promise<PackageManagerCommandRunResult>;
41
38
  export declare function copyPackageManagerProjectFiles(options: {
@@ -1,2 +1,2 @@
1
- import{forceRemove as e,getSandboxUserEnvOverrides as t,killSandboxUserProcesses as n,makeAccessibleToSandboxUser as r,prependInsideSandboxWrapper as i,sandboxUserName as a,startSandboxTimeoutWatchdog as o,wrapCommandWithSandboxUser as s}from"./sandboxUser.js";import{copyWithoutFollowingSymlinks as c,createDirectoryWithoutFollowingSymlinks as l}from"./safeFs.js";import u from"node:fs";import d from"node:path";import f from"node:child_process";import p from"node:os";import m from"node:fs/promises";const h={bun:[`package.json`,`bun.lock`,`bun.lockb`],cargo:[`Cargo.toml`,`Cargo.lock`],go:[`go.mod`,`go.sum`],gradle:[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradle.properties`,`gradle.lockfile`,`buildscript-gradle.lockfile`,`gradle`,`gradlew`,`gradlew.bat`],maven:[`pom.xml`,`.mvn`,`mvnw`,`mvnw.cmd`],npm:[`package.json`,`package-lock.json`],pnpm:[`package.json`,`pnpm-lock.yaml`,`pnpm-workspace.yaml`],ruby:[`Gemfile`,`Gemfile.lock`,`.ruby-version`],uv:[`pyproject.toml`,`uv.lock`],yarn:[`package.json`,`yarn.lock`,`.yarnrc`,`.yarnrc.yml`,`.yarn`]},g={bun:S,cargo:C,go:w,gradle:T,maven:E,npm:D,pnpm:O,ruby:k,uv:A,yarn:j},_=z();async function v(t){let i=await m.mkdtemp(d.join(p.tmpdir(),t.tempDirPrefix??`exercode-`));try{await m.cp(t.cwd,i,{recursive:!0}),await I({packageManager:t.packageManager,projectDir:t.projectDir,runDir:i,projectFilePaths:t.projectFilePaths}),r(i);let e=t.env?{...process.env,...t.env}:process.env,n=t.prepareDependencies===!1?void 0:await b(t.packageManager,i),a=typeof t.command==`function`?t.command({runDir:i}):t.command,o=Date.now(),s=t.outputLimitBytes??52428800,c;if(n&&(c=await R(n,{cwd:i,env:e,outputLimitBytes:s,stdin:``,timeLimitSeconds:t.timeLimitSeconds}),x(c)))return y({elapsedTimeSeconds:(Date.now()-o)/1e3,options:t,result:c});let l=t.timeLimitSeconds-(Date.now()-o)/1e3;if(l<=0)return{stdin:t.stdin??``,stdout:c?.stdout??``,stderr:c?.stderr??``,status:0,timeSeconds:t.timeLimitSeconds+.001,memoryBytes:c?.memoryBytes??0,timedOut:!0,signal:c?.signal,outputLimitExceeded:!1};let u=await R(a,{cwd:i,env:e,outputLimitBytes:s,stdin:t.stdin??``,timeLimitSeconds:l}),d=(Date.now()-o)/1e3;return y(c?{elapsedTimeSeconds:d,options:t,result:{...u,timeSeconds:c.timeSeconds+u.timeSeconds,memoryBytes:Math.max(c.memoryBytes,u.memoryBytes)}}:{elapsedTimeSeconds:d,options:t,result:u})}finally{try{a&&n()}finally{await e(i)}}}function y(e){return{stdin:e.options.stdin??``,stdout:e.result.stdout,stderr:e.result.stderr,status:e.result.timedOut||e.result.outputLimitExceeded?0:e.result.status,timeSeconds:e.result.timedOut?e.options.timeLimitSeconds+.001:e.result.timeSeconds||e.elapsedTimeSeconds,memoryBytes:e.result.memoryBytes,timedOut:e.result.timedOut,signal:e.result.signal,outputLimitExceeded:e.result.outputLimitExceeded}}function b(e,t){return g[e](t)}function x(e){return e.status!==0||e.timedOut||e.outputLimitExceeded}async function S(e){if(await P(d.join(e,`package.json`)))return await N(e,[`bun.lock`,`bun.lockb`])?[`bun`,`install`,`--frozen-lockfile`,`--silent`]:[`bun`,`install`,`--silent`]}async function C(e){if(await P(d.join(e,`Cargo.toml`)))return await P(d.join(e,`Cargo.lock`))?[`cargo`,`fetch`,`--locked`]:[`cargo`,`fetch`]}async function w(e){if(await P(d.join(e,`go.mod`)))return[`go`,`mod`,`download`]}async function T(e){if(!await N(e,[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradlew`,`gradlew.bat`]))return;let t=[`--no-daemon`,`--quiet`,`dependencies`];return process.platform===`win32`?await P(d.join(e,`gradlew.bat`))?[`cmd.exe`,`/c`,`gradlew.bat`,...t]:[`gradle`,...t]:await P(d.join(e,`gradlew`))?[`sh`,`./gradlew`,...t]:[`gradle`,...t]}async function E(e){if(!await P(d.join(e,`pom.xml`)))return;let t=[`-q`,`dependency:go-offline`];return process.platform===`win32`?await P(d.join(e,`mvnw.cmd`))?[`cmd.exe`,`/c`,`mvnw.cmd`,...t]:[`mvn`,...t]:await P(d.join(e,`mvnw`))?[`sh`,`./mvnw`,...t]:[`mvn`,...t]}async function D(e){if(await P(d.join(e,`package.json`)))return await P(d.join(e,`package-lock.json`))?[`npm`,`ci`,`--silent`]:[`npm`,`install`,`--silent`]}async function O(e){if(await P(d.join(e,`package.json`)))return await P(d.join(e,`pnpm-lock.yaml`))?[`pnpm`,`install`,`--frozen-lockfile`,`--silent`]:[`pnpm`,`install`,`--silent`]}async function k(e){if(await P(d.join(e,`Gemfile`)))return await P(d.join(e,`Gemfile.lock`))?[`bundle`,`install`,`--frozen`,`--quiet`]:[`bundle`,`install`,`--quiet`]}async function A(){}async function j(e){if(!await P(d.join(e,`package.json`)))return;let t=await M(e),n=await P(d.join(e,`yarn.lock`));return t?n?[`yarn`,`install`,`--immutable`]:[`yarn`,`install`]:n?[`yarn`,`install`,`--frozen-lockfile`,`--silent`]:[`yarn`,`install`,`--silent`]}async function M(e){if(await P(d.join(e,`.yarnrc.yml`)))return!0;let t=await F(d.join(e,`package.json`)),n=typeof t.packageManager==`string`?t.packageManager:void 0,r=/^yarn@(\d+)/.exec(n??``)?.[1];return r!==void 0&&Number(r)>=2}async function N(e,t){for(let n of t)if(await P(d.join(e,n)))return!0;return!1}async function P(e){try{return await m.access(e),!0}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e;return!1}}async function F(e){try{let t=JSON.parse(await m.readFile(e,`utf8`));return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch(e){if(e instanceof SyntaxError||(typeof e==`object`&&e&&`code`in e?e.code:void 0)===`ENOENT`)return{};throw e}}async function I(e){for(let t of e.projectFilePaths??h[e.packageManager])await L(d.join(e.projectDir,t),d.join(e.runDir,t),e.runDir)}async function L(e,t,n){try{await m.lstat(e),await l(n,d.dirname(t)),await c(e,t)}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e}}async function R(e,n){let r=_===void 0?void 0:d.join(n.cwd,`.exercode-time-result`),a=s(e),c=_===void 0?a:i(a,[..._,`--output=${r}`]),l=o(n.timeLimitSeconds),u=Date.now()+(Math.ceil(n.timeLimitSeconds)+5)*1e3,p;try{p=f.spawn(c[0],c.slice(1),{cwd:n.cwd,detached:process.platform!==`win32`,env:{...n.env,...t(n.env)},stdio:[`pipe`,`pipe`,`pipe`]})}catch(e){throw l.cancel(),e}let m=[],h=[],g=0,v=!1,y=!1,b,x,S=e=>{try{B(p,e)}catch(e){b??=e instanceof Error?e:Error(String(e)),x?.()}},C=(e,t)=>{if(g>=n.outputLimitBytes){t.byteLength>0&&(y=!0,S(`SIGKILL`));return}let r=n.outputLimitBytes-g,i=t.byteLength>r?t.subarray(0,r):t;e.push(i),g+=i.byteLength,t.byteLength>r&&(y=!0,S(`SIGKILL`))};p.stdout.on(`data`,e=>C(m,e)),p.stderr.on(`data`,e=>C(h,e));let w=setTimeout(()=>{v=!0,S(`SIGTERM`)},n.timeLimitSeconds*1e3),T=setTimeout(()=>{v&&S(`SIGKILL`)},n.timeLimitSeconds*1e3+1e3);T.unref();let E,D=!1,{status:O,signal:k}=await new Promise((e,t)=>{let r=!1,i,a=e=>{r||(i=e,S(`SIGKILL`),p.pid===void 0&&(r=!0,t(e)))};x=()=>{E??=setTimeout(()=>{r||(r=!0,t(b??Error(`failed to terminate the submission`)))},Math.max(0,u-Date.now())+2e3)},p.on(`error`,a),p.stdin.on(`error`,e=>{e.code!==`EPIPE`&&a(e)}),p.on(`close`,(n,a)=>{if(!r){if(r=!0,D=!0,i){t(i);return}e({status:n??void 0,signal:a??void 0})}}),p.stdin.end(n.stdin)}).finally(()=>{clearTimeout(w),clearTimeout(T),E&&clearTimeout(E),(D||!b)&&l.cancel()}),{timeSeconds:A,memoryBytes:j}=r===void 0?{timeSeconds:0,memoryBytes:0}:await H(r);return{stdout:Buffer.concat(m).toString(),stderr:Buffer.concat(h).toString(),status:O,timeSeconds:A,memoryBytes:j,timedOut:v,signal:k,outputLimitExceeded:y}}function z(){let e=p.platform()===`darwin`?`gtime`:`/usr/bin/time`,t=f.spawnSync(e,[`--version`],{stdio:`ignore`});if(!(t.error||t.status!==0))return[e,`--format`,`%e %M`]}function B(e,t){if(e.pid!==void 0){if(a){n([t===`SIGKILL`?`KILL`:`TERM`]);return}try{if(process.platform===`win32`){e.kill(t);return}process.kill(-e.pid,t)}catch(e){let t=typeof e==`object`&&e&&`code`in e?e.code:void 0;if(t!==`ESRCH`&&t!==`EPERM`)throw e}}}function V(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function H(e){let t,n;try{if(n=await m.open(e,u.constants.O_RDONLY|u.constants.O_NOFOLLOW|u.constants.O_NONBLOCK),!(await n.stat()).isFile())throw Error(`${e} is not a regular file`);t=await n.readFile(`utf8`)}catch(t){if(V(t,`ENOENT`))return{timeSeconds:0,memoryBytes:0};throw Error(`failed to read the time measurement at ${e}`,{cause:t})}finally{await n?.close()}let r=/(\d+(?:[.,]\d+)?) (\d+)\s*$/.exec(t);return r?{timeSeconds:Number(r[1].replace(`,`,`.`)),memoryBytes:Number(r[2])*1024}:{timeSeconds:0,memoryBytes:0}}export{I as copyPackageManagerProjectFiles,v as runCommandInTemporaryPackageManagerProject};
1
+ import{forciblyRemoveDirectory as e}from"./temporaryProblemDirCopy.js";import t from"node:path";import n from"node:fs/promises";import r from"node:child_process";import i from"node:os";const a={bun:[`package.json`,`bun.lock`,`bun.lockb`],cargo:[`Cargo.toml`,`Cargo.lock`],go:[`go.mod`,`go.sum`],gradle:[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradle.properties`,`gradle.lockfile`,`buildscript-gradle.lockfile`,`gradle`,`gradlew`,`gradlew.bat`],maven:[`pom.xml`,`.mvn`,`mvnw`,`mvnw.cmd`],npm:[`package.json`,`package-lock.json`],pnpm:[`package.json`,`pnpm-lock.yaml`,`pnpm-workspace.yaml`],ruby:[`Gemfile`,`Gemfile.lock`,`.ruby-version`],uv:[`pyproject.toml`,`uv.lock`],yarn:[`package.json`,`yarn.lock`,`.yarnrc`,`.yarnrc.yml`,`.yarn`]},o={bun:f,cargo:p,go:m,gradle:h,maven:g,npm:_,pnpm:v,ruby:y,uv:b,yarn:x},s=k();async function c(r){let a=await n.mkdtemp(t.join(i.tmpdir(),r.tempDirPrefix??`exercode-`));try{await n.cp(r.cwd,a,{recursive:!0}),await E({packageManager:r.packageManager,projectDir:r.projectDir,runDir:a,projectFilePaths:r.projectFilePaths});let e=r.env?{...process.env,...r.env}:process.env,t=r.prepareDependencies===!1?void 0:await u(r.packageManager,a),i=typeof r.command==`function`?r.command({runDir:a}):r.command,o=Date.now(),s=r.outputLimitBytes??52428800,c;if(t&&(c=await O(t,{cwd:a,env:e,outputLimitBytes:s,stdin:``,timeLimitSeconds:r.timeLimitSeconds}),d(c)))return l({elapsedTimeSeconds:(Date.now()-o)/1e3,options:r,result:c});let f=r.timeLimitSeconds-(Date.now()-o)/1e3;if(f<=0)return{stdin:r.stdin??``,stdout:c?.stdout??``,stderr:c?.stderr??``,status:0,timeSeconds:r.timeLimitSeconds+.001,memoryBytes:c?.memoryBytes??0,timedOut:!0,signal:c?.signal,outputLimitExceeded:!1};let p=await O(i,{cwd:a,env:e,outputLimitBytes:s,stdin:r.stdin??``,timeLimitSeconds:f}),m=(Date.now()-o)/1e3;return l(c?{elapsedTimeSeconds:m,options:r,result:{...p,timeSeconds:c.timeSeconds+p.timeSeconds,memoryBytes:Math.max(c.memoryBytes,p.memoryBytes)}}:{elapsedTimeSeconds:m,options:r,result:p})}finally{await e(a)}}function l(e){return{stdin:e.options.stdin??``,stdout:e.result.stdout,stderr:e.result.stderr,status:e.result.timedOut||e.result.outputLimitExceeded?0:e.result.status,timeSeconds:e.result.timedOut?e.options.timeLimitSeconds+.001:e.result.timeSeconds||e.elapsedTimeSeconds,memoryBytes:e.result.memoryBytes,timedOut:e.result.timedOut,signal:e.result.signal,outputLimitExceeded:e.result.outputLimitExceeded}}function u(e,t){return o[e](t)}function d(e){return e.status!==0||e.timedOut||e.outputLimitExceeded}async function f(e){if(await w(t.join(e,`package.json`)))return await C(e,[`bun.lock`,`bun.lockb`])?[`bun`,`install`,`--frozen-lockfile`,`--silent`]:[`bun`,`install`,`--silent`]}async function p(e){if(await w(t.join(e,`Cargo.toml`)))return await w(t.join(e,`Cargo.lock`))?[`cargo`,`fetch`,`--locked`]:[`cargo`,`fetch`]}async function m(e){if(await w(t.join(e,`go.mod`)))return[`go`,`mod`,`download`]}async function h(e){if(!await C(e,[`build.gradle`,`build.gradle.kts`,`settings.gradle`,`settings.gradle.kts`,`gradlew`,`gradlew.bat`]))return;let n=[`--no-daemon`,`--quiet`,`dependencies`];return process.platform===`win32`?await w(t.join(e,`gradlew.bat`))?[`cmd.exe`,`/c`,`gradlew.bat`,...n]:[`gradle`,...n]:await w(t.join(e,`gradlew`))?[`sh`,`./gradlew`,...n]:[`gradle`,...n]}async function g(e){if(!await w(t.join(e,`pom.xml`)))return;let n=[`-q`,`dependency:go-offline`];return process.platform===`win32`?await w(t.join(e,`mvnw.cmd`))?[`cmd.exe`,`/c`,`mvnw.cmd`,...n]:[`mvn`,...n]:await w(t.join(e,`mvnw`))?[`sh`,`./mvnw`,...n]:[`mvn`,...n]}async function _(e){if(await w(t.join(e,`package.json`)))return await w(t.join(e,`package-lock.json`))?[`npm`,`ci`,`--silent`]:[`npm`,`install`,`--silent`]}async function v(e){if(await w(t.join(e,`package.json`)))return await w(t.join(e,`pnpm-lock.yaml`))?[`pnpm`,`install`,`--frozen-lockfile`,`--silent`]:[`pnpm`,`install`,`--silent`]}async function y(e){if(await w(t.join(e,`Gemfile`)))return await w(t.join(e,`Gemfile.lock`))?[`bundle`,`install`,`--frozen`,`--quiet`]:[`bundle`,`install`,`--quiet`]}async function b(){}async function x(e){if(!await w(t.join(e,`package.json`)))return;let n=await S(e),r=await w(t.join(e,`yarn.lock`));return n?r?[`yarn`,`install`,`--immutable`]:[`yarn`,`install`]:r?[`yarn`,`install`,`--frozen-lockfile`,`--silent`]:[`yarn`,`install`,`--silent`]}async function S(e){if(await w(t.join(e,`.yarnrc.yml`)))return!0;let n=await T(t.join(e,`package.json`)),r=typeof n.packageManager==`string`?n.packageManager:void 0,i=/^yarn@(\d+)/.exec(r??``)?.[1];return i!==void 0&&Number(i)>=2}async function C(e,n){for(let r of n)if(await w(t.join(e,r)))return!0;return!1}async function w(e){try{return await n.access(e),!0}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e;return!1}}async function T(e){try{let t=JSON.parse(await n.readFile(e,`utf8`));return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch(e){if(e instanceof SyntaxError||(typeof e==`object`&&e&&`code`in e?e.code:void 0)===`ENOENT`)return{};throw e}}async function E(e){for(let n of e.projectFilePaths??a[e.packageManager])await D(t.join(e.projectDir,n),t.join(e.runDir,n))}async function D(e,r){try{await n.lstat(e),await n.mkdir(t.dirname(r),{recursive:!0}),await n.cp(e,r,{force:!0,recursive:!0})}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`ENOENT`)throw e}}async function O(e,n){let i=s===void 0?void 0:t.join(n.cwd,`.exercode-time-result`),a=s===void 0?e:[...s,`--output=${i}`,...e],o=r.spawn(a[0],a.slice(1),{cwd:n.cwd,detached:process.platform!==`win32`,env:n.env,stdio:[`pipe`,`pipe`,`pipe`]}),c=[],l=[],u=0,d=!1,f=!1,p=(e,t)=>{if(u>=n.outputLimitBytes){t.byteLength>0&&(f=!0,A(o,`SIGKILL`));return}let r=n.outputLimitBytes-u,i=t.byteLength>r?t.subarray(0,r):t;e.push(i),u+=i.byteLength,t.byteLength>r&&(f=!0,A(o,`SIGKILL`))};o.stdout.on(`data`,e=>p(c,e)),o.stderr.on(`data`,e=>p(l,e));let m=setTimeout(()=>{d=!0,A(o,`SIGTERM`)},n.timeLimitSeconds*1e3),h=setTimeout(()=>{d&&A(o,`SIGKILL`)},n.timeLimitSeconds*1e3+1e3);h.unref();let{status:g,signal:_}=await new Promise((e,t)=>{let r=!1,i,a=e=>{r||(i=e,A(o,`SIGKILL`),o.pid===void 0&&(r=!0,t(e)))};o.on(`error`,a),o.stdin.on(`error`,e=>{e.code!==`EPIPE`&&a(e)}),o.on(`close`,(n,a)=>{if(!r){if(r=!0,i){t(i);return}e({status:n??void 0,signal:a??void 0})}}),o.stdin.end(n.stdin)}).finally(()=>{clearTimeout(m),clearTimeout(h)}),{timeSeconds:v,memoryBytes:y}=i===void 0?{timeSeconds:0,memoryBytes:0}:await M(i);return{stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(l).toString(),status:g,timeSeconds:v,memoryBytes:y,timedOut:d,signal:_,outputLimitExceeded:f}}function k(){let e=i.platform()===`darwin`?`gtime`:`/usr/bin/time`,t=r.spawnSync(e,[`--version`],{stdio:`ignore`});if(!(t.error||t.status!==0))return[e,`--format`,`%e %M`]}function A(e,t){if(e.pid!==void 0)try{if(process.platform===`win32`){e.kill(t);return}process.kill(-e.pid,t)}catch(e){let t=typeof e==`object`&&e&&`code`in e?e.code:void 0;if(t!==`ESRCH`&&t!==`EPERM`)throw e}}function j(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}async function M(e){let t;try{t=await n.readFile(e,`utf8`)}catch(e){if(j(e,`ENOENT`))return{timeSeconds:0,memoryBytes:0};throw e}let r=/(\d+(?:[.,]\d+)?) (\d+)\s*$/.exec(t);return r?{timeSeconds:Number(r[1].replace(`,`,`.`)),memoryBytes:Number(r[2])*1024}:{timeSeconds:0,memoryBytes:0}}export{E as copyPackageManagerProjectFiles,c as runCommandInTemporaryPackageManagerProject};
2
2
  //# sourceMappingURL=runCommandInTemporaryPackageManagerProject.js.map