@exercode/problem-utils 2.4.3 → 3.0.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 (79) hide show
  1. package/dist/cli/checkAllProblems.cjs +1 -1
  2. package/dist/cli/checkAllProblems.cjs.map +1 -1
  3. package/dist/cli/checkAllProblems.js +1 -1
  4. package/dist/cli/checkAllProblems.js.map +1 -1
  5. package/dist/helpers/checkProblemDirIsolation.cjs +1 -1
  6. package/dist/helpers/checkProblemDirIsolation.js +1 -1
  7. package/dist/helpers/cleanWorkingDirectory.cjs +1 -1
  8. package/dist/helpers/cleanWorkingDirectory.cjs.map +1 -1
  9. package/dist/helpers/cleanWorkingDirectory.d.ts +2 -6
  10. package/dist/helpers/cleanWorkingDirectory.js +1 -1
  11. package/dist/helpers/cleanWorkingDirectory.js.map +1 -1
  12. package/dist/helpers/compareExpectedOutputFiles.cjs +1 -1
  13. package/dist/helpers/compareExpectedOutputFiles.cjs.map +1 -1
  14. package/dist/helpers/compareExpectedOutputFiles.js +1 -1
  15. package/dist/helpers/compareExpectedOutputFiles.js.map +1 -1
  16. package/dist/helpers/copyTestCaseFileInput.cjs +1 -1
  17. package/dist/helpers/copyTestCaseFileInput.cjs.map +1 -1
  18. package/dist/helpers/copyTestCaseFileInput.js +1 -1
  19. package/dist/helpers/copyTestCaseFileInput.js.map +1 -1
  20. package/dist/helpers/readOutputFiles.cjs +1 -1
  21. package/dist/helpers/readOutputFiles.cjs.map +1 -1
  22. package/dist/helpers/readOutputFiles.d.ts +0 -9
  23. package/dist/helpers/readOutputFiles.js +1 -1
  24. package/dist/helpers/readOutputFiles.js.map +1 -1
  25. package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs +1 -1
  26. package/dist/helpers/runCommandInTemporaryPackageManagerProject.cjs.map +1 -1
  27. package/dist/helpers/runCommandInTemporaryPackageManagerProject.d.ts +0 -3
  28. package/dist/helpers/runCommandInTemporaryPackageManagerProject.js +1 -1
  29. package/dist/helpers/runCommandInTemporaryPackageManagerProject.js.map +1 -1
  30. package/dist/helpers/spawnSyncWithTimeout.cjs +1 -1
  31. package/dist/helpers/spawnSyncWithTimeout.cjs.map +1 -1
  32. package/dist/helpers/spawnSyncWithTimeout.d.ts +0 -7
  33. package/dist/helpers/spawnSyncWithTimeout.js +1 -1
  34. package/dist/helpers/spawnSyncWithTimeout.js.map +1 -1
  35. package/dist/helpers/startHttpServer.cjs +1 -1
  36. package/dist/helpers/startHttpServer.cjs.map +1 -1
  37. package/dist/helpers/startHttpServer.js +1 -1
  38. package/dist/helpers/startHttpServer.js.map +1 -1
  39. package/dist/index.cjs +1 -1
  40. package/dist/index.d.ts +0 -2
  41. package/dist/index.js +1 -1
  42. package/dist/presets/command.cjs +1 -1
  43. package/dist/presets/command.cjs.map +1 -1
  44. package/dist/presets/command.d.ts +0 -16
  45. package/dist/presets/command.js +1 -1
  46. package/dist/presets/command.js.map +1 -1
  47. package/dist/presets/evaluation.cjs +4 -4
  48. package/dist/presets/evaluation.cjs.map +1 -1
  49. package/dist/presets/evaluation.js +4 -4
  50. package/dist/presets/evaluation.js.map +1 -1
  51. package/dist/presets/guiCommand.cjs +3 -3
  52. package/dist/presets/guiCommand.cjs.map +1 -1
  53. package/dist/presets/guiCommand.d.ts +0 -24
  54. package/dist/presets/guiCommand.js +3 -3
  55. package/dist/presets/guiCommand.js.map +1 -1
  56. package/dist/presets/stdio.cjs +1 -1
  57. package/dist/presets/stdio.cjs.map +1 -1
  58. package/dist/presets/stdio.js +1 -1
  59. package/dist/presets/stdio.js.map +1 -1
  60. package/dist/types/language.cjs +2 -2
  61. package/dist/types/language.cjs.map +1 -1
  62. package/dist/types/language.js +2 -2
  63. package/dist/types/language.js.map +1 -1
  64. package/package.json +2 -2
  65. package/dist/helpers/runCustomRunner.cjs +0 -2
  66. package/dist/helpers/runCustomRunner.cjs.map +0 -1
  67. package/dist/helpers/runCustomRunner.d.ts +0 -8
  68. package/dist/helpers/runCustomRunner.js +0 -2
  69. package/dist/helpers/runCustomRunner.js.map +0 -1
  70. package/dist/helpers/safeFs.cjs +0 -2
  71. package/dist/helpers/safeFs.cjs.map +0 -1
  72. package/dist/helpers/safeFs.d.ts +0 -29
  73. package/dist/helpers/safeFs.js +0 -2
  74. package/dist/helpers/safeFs.js.map +0 -1
  75. package/dist/helpers/sandboxUser.cjs +0 -3
  76. package/dist/helpers/sandboxUser.cjs.map +0 -1
  77. package/dist/helpers/sandboxUser.d.ts +0 -146
  78. package/dist/helpers/sandboxUser.js +0 -3
  79. package/dist/helpers/sandboxUser.js.map +0 -1
@@ -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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"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 { timeSeconds: 0, memoryBytes: 0 };\n\n return { timeSeconds: Number(match[1]!.replace(',', '.')), memoryBytes: Number(match[2]) * 1024 };\n}\n"],"mappings":"2SAwCA,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,CACvE,EAEM,EAAwC,CAC5C,IAAK,EACL,MAAO,EACP,GAAI,EACJ,OAAQ,EACR,MAAO,EACP,IAAK,EACL,KAAM,EACN,KAAM,EACN,GAAI,EACJ,KAAM,CACR,EAIM,EAAc,EAAmB,EAOvC,eAAsB,EACpB,EACyC,CACzC,IAAM,EAAS,MAAMA,EAAAA,QAAG,QAAQC,EAAAA,QAAK,KAAKC,EAAAA,QAAG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IAAS,QAAS,MAAM,CAClD,CACF,CAEA,SAAS,EAAgB,EAAgB,EAAuB,CAC9D,OAAO,OAAO,GAAU,YAAY,GAAkB,SAAU,GAAU,EAA4B,OAAS,CACjH,CAEA,eAAe,EAAe,EAA+E,CAI3G,IAAI,EACJ,GAAI,CACF,EAAU,MAAMJ,EAAAA,QAAG,SAAS,EAAgB,MAAM,CACpD,OAAS,EAAO,CACd,GAAI,EAAgB,EAAO,QAAQ,EAAG,MAAO,CAAE,YAAa,EAAG,YAAa,CAAE,EAC9E,MAAM,CACR,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"}
@@ -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
@@ -1 +1 @@
1
- {"version":3,"file":"runCommandInTemporaryPackageManagerProject.js","names":["fs","childProcess","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":"sfAoDA,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,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O,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.js","names":["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 { timeSeconds: 0, memoryBytes: 0 };\n\n return { timeSeconds: Number(match[1]!.replace(',', '.')), memoryBytes: Number(match[2]) * 1024 };\n}\n"],"mappings":"yLAwCA,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,iB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M,EACJ,OAAO,GAAU,UAAY,GAAkB,SAAU,EAAS,EAA4B,KAAO,IAAA,GACvG,GAAI,IAAS,SAAW,IAAS,QAAS,MAAM,CAClD,CACF,CAEA,SAAS,EAAgB,EAAgB,EAAuB,CAC9D,OAAO,OAAO,GAAU,YAAY,GAAkB,SAAU,GAAU,EAA4B,OAAS,CACjH,CAEA,eAAe,EAAe,EAA+E,CAI3G,IAAI,EACJ,GAAI,CACF,EAAU,MAAM,EAAG,SAAS,EAAgB,MAAM,CACpD,OAAS,EAAO,CACd,GAAI,EAAgB,EAAO,QAAQ,EAAG,MAAO,CAAE,YAAa,EAAG,YAAa,CAAE,EAC9E,MAAM,CACR,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,2 +1,2 @@
1
- "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("./sandboxUser.cjs");let n=require("node:child_process");n=e.__toESM(n,1);let r=require("node:os");r=e.__toESM(r,1);const i=[r.default.platform()===`darwin`?`gtime`:`/usr/bin/time`,`--format`,`%e %M`];function a(e,r,a,o){let s=Date.now(),c={...a.env??process.env},l=t.wrapCommandWithSandboxUser([t.TIMEOUT_COMMAND,o.toFixed(3),...i,e,...r]),u=t.startSandboxTimeoutWatchdog(o),d,f;try{d=n.default.spawnSync(l[0],l.slice(1),{...a,env:{...c,...t.getSandboxUserEnvOverrides(c)}})}finally{f=u.fired(),u.cancel(),t.sandboxUserName&&t.killSandboxUserProcesses()}let p=Date.now(),m=/(?:^|\n)(\d+\.\d+) (\d+)\s*$/.exec(d.stderr),h=m?d.stderr.slice(0,m.index):d.stderr,g=Number(m?.[1])||(p-s)/1e3,_=Number(m?.[2])*1024||0;return d.status===124||f?{...d,status:0,stderr:h,timeSeconds:o+.001,memoryBytes:_}:{...d,stderr:h,timeSeconds:g,memoryBytes:_}}exports.spawnSyncWithTimeout=a;
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("node:child_process");t=e.__toESM(t,1);let n=require("node:os");n=e.__toESM(n,1);const r=[n.default.platform()===`darwin`?`gtime`:`/usr/bin/time`,`--format`,`%e %M`];function i(e,n,i,a){let o=Date.now(),s=t.default.spawnSync(`timeout`,[a.toFixed(3),...r,e,...n],i),c=Date.now(),l=/(?:^|\n)(\d+\.\d+) (\d+)\s*$/.exec(s.stderr),u=l?s.stderr.slice(0,l.index):s.stderr,d=Number(l?.[1])||(c-o)/1e3,f=Number(l?.[2])*1024||0;return s.status===124?{...s,status:0,stderr:u,timeSeconds:a+.001,memoryBytes:f}:{...s,stderr:u,timeSeconds:d,memoryBytes:f}}exports.spawnSyncWithTimeout=i;
2
2
  //# sourceMappingURL=spawnSyncWithTimeout.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"spawnSyncWithTimeout.cjs","names":["os","wrapCommandWithSandboxUser","TIMEOUT_COMMAND","startSandboxTimeoutWatchdog","child_process","getSandboxUserEnvOverrides","sandboxUserName"],"sources":["../../src/helpers/spawnSyncWithTimeout.ts"],"sourcesContent":["import child_process from 'node:child_process';\nimport os from 'node:os';\n\nimport {\n getSandboxUserEnvOverrides,\n killSandboxUserProcesses,\n sandboxUserName,\n startSandboxTimeoutWatchdog,\n TIMEOUT_COMMAND,\n wrapCommandWithSandboxUser,\n} from './sandboxUser.js';\n\nconst TIME_COMMAND = [os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time', '--format', '%e %M'] as const;\n\n/**\n * Run an untrusted (submission-derived) command with a timeout. When a judge server delegates\n * untrusted execution via `EXERCODE_SANDBOX_USER` (see `sandboxUser.ts`), the whole command,\n * including `timeout`, runs as the sandbox user so the timer can signal the sandboxed process; a\n * harness-owned watchdog enforces the deadline even if the submission kills its own `timeout`, and\n * leftover sandbox processes (e.g. daemonized children) are killed after every run.\n */\nexport function spawnSyncWithTimeout(\n command: string,\n args: readonly string[],\n options: child_process.SpawnSyncOptionsWithStringEncoding,\n timeoutSeconds: number\n): child_process.SpawnSyncReturns<string> & { timeSeconds: number; memoryBytes: number } {\n const startTimeMilliseconds = Date.now();\n\n const env = { ...(options.env ?? process.env) };\n const wrappedCommand = wrapCommandWithSandboxUser([\n TIMEOUT_COMMAND,\n timeoutSeconds.toFixed(3),\n ...TIME_COMMAND,\n command,\n ...args,\n ]);\n const watchdog = startSandboxTimeoutWatchdog(timeoutSeconds);\n let spawnResult: child_process.SpawnSyncReturns<string>;\n let watchdogFired: boolean;\n try {\n spawnResult = child_process.spawnSync(wrappedCommand[0], wrappedCommand.slice(1), {\n ...options,\n env: { ...env, ...getSandboxUserEnvOverrides(env) },\n });\n } finally {\n // Read the watchdog state before cancelling, then always cancel: a leaked watchdog is detached\n // and would SIGKILL a later request's submission.\n watchdogFired = watchdog.fired();\n watchdog.cancel();\n if (sandboxUserName) killSandboxUserProcesses();\n }\n\n const stopTimeMilliseconds = Date.now();\n\n const match = /(?:^|\\n)(\\d+\\.\\d+) (\\d+)\\s*$/.exec(spawnResult.stderr);\n const stderr = match ? spawnResult.stderr.slice(0, match.index) : spawnResult.stderr;\n const timeSeconds = Number(match?.[1]) || (stopTimeMilliseconds - startTimeMilliseconds) / 1000;\n const memoryBytes = Number(match?.[2]) * 1024 || 0;\n\n // `timeout` reports 124, but a sandboxed submission can kill its own same-UID `timeout` and be\n // stopped by the watchdog instead, which surfaces as a signal-derived status. Both are timeouts:\n // reporting the latter as a runtime error would mislabel a submission that outran its deadline.\n if (spawnResult.status === 124 || watchdogFired) {\n return { ...spawnResult, status: 0, stderr, timeSeconds: timeoutSeconds + 1e-3, memoryBytes };\n }\n\n return { ...spawnResult, stderr, timeSeconds, memoryBytes };\n}\n"],"mappings":"gMAYA,MAAM,EAAe,CAACA,EAAAA,QAAG,SAAS,IAAM,SAAW,QAAU,gBAAiB,WAAY,OAAO,EASjG,SAAgB,EACd,EACA,EACA,EACA,EACuF,CACvF,IAAM,EAAwB,KAAK,IAAI,EAEjC,EAAM,CAAE,GAAI,EAAQ,KAAO,QAAQ,GAAK,EACxC,EAAiBC,EAAAA,2BAA2B,CAChDC,EAAAA,gBACA,EAAe,QAAQ,CAAC,EACxB,GAAG,EACH,EACA,GAAG,CACL,CAAC,EACK,EAAWC,EAAAA,4BAA4B,CAAc,EACvD,EACA,EACJ,GAAI,CACF,EAAcC,EAAAA,QAAc,UAAU,EAAe,GAAI,EAAe,MAAM,CAAC,EAAG,CAChF,GAAG,EACH,IAAK,CAAE,GAAG,EAAK,GAAGC,EAAAA,2BAA2B,CAAG,CAAE,CACpD,CAAC,CACH,QAAU,CAGR,EAAgB,EAAS,MAAM,EAC/B,EAAS,OAAO,EACZC,EAAAA,iBAAiB,EAAA,yBAAyB,CAChD,CAEA,IAAM,EAAuB,KAAK,IAAI,EAEhC,EAAQ,+BAA+B,KAAK,EAAY,MAAM,EAC9D,EAAS,EAAQ,EAAY,OAAO,MAAM,EAAG,EAAM,KAAK,EAAI,EAAY,OACxE,EAAc,OAAO,IAAQ,EAAE,IAAM,EAAuB,GAAyB,IACrF,EAAc,OAAO,IAAQ,EAAE,EAAI,MAAQ,EASjD,OAJI,EAAY,SAAW,KAAO,EACzB,CAAE,GAAG,EAAa,OAAQ,EAAG,SAAQ,YAAa,EAAiB,KAAM,aAAY,EAGvF,CAAE,GAAG,EAAa,SAAQ,cAAa,aAAY,CAC5D"}
1
+ {"version":3,"file":"spawnSyncWithTimeout.cjs","names":["os","child_process"],"sources":["../../src/helpers/spawnSyncWithTimeout.ts"],"sourcesContent":["import child_process from 'node:child_process';\nimport os from 'node:os';\n\nconst TIME_COMMAND = [os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time', '--format', '%e %M'] as const;\n\nexport function spawnSyncWithTimeout(\n command: string,\n args: readonly string[],\n options: child_process.SpawnSyncOptionsWithStringEncoding,\n timeoutSeconds: number\n): child_process.SpawnSyncReturns<string> & { timeSeconds: number; memoryBytes: number } {\n const startTimeMilliseconds = Date.now();\n\n const spawnResult = child_process.spawnSync(\n 'timeout',\n [timeoutSeconds.toFixed(3), ...TIME_COMMAND, command, ...args],\n options\n );\n\n const stopTimeMilliseconds = Date.now();\n\n const match = /(?:^|\\n)(\\d+\\.\\d+) (\\d+)\\s*$/.exec(spawnResult.stderr);\n const stderr = match ? spawnResult.stderr.slice(0, match.index) : spawnResult.stderr;\n const timeSeconds = Number(match?.[1]) || (stopTimeMilliseconds - startTimeMilliseconds) / 1000;\n const memoryBytes = Number(match?.[2]) * 1024 || 0;\n\n // timeout\n if (spawnResult.status === 124) {\n return { ...spawnResult, status: 0, stderr, timeSeconds: timeoutSeconds + 1e-3, memoryBytes };\n }\n\n return { ...spawnResult, stderr, timeSeconds, memoryBytes };\n}\n"],"mappings":"iKAGA,MAAM,EAAe,CAACA,EAAAA,QAAG,SAAS,IAAM,SAAW,QAAU,gBAAiB,WAAY,OAAO,EAEjG,SAAgB,EACd,EACA,EACA,EACA,EACuF,CACvF,IAAM,EAAwB,KAAK,IAAI,EAEjC,EAAcC,EAAAA,QAAc,UAChC,UACA,CAAC,EAAe,QAAQ,CAAC,EAAG,GAAG,EAAc,EAAS,GAAG,CAAI,EAC7D,CACF,EAEM,EAAuB,KAAK,IAAI,EAEhC,EAAQ,+BAA+B,KAAK,EAAY,MAAM,EAC9D,EAAS,EAAQ,EAAY,OAAO,MAAM,EAAG,EAAM,KAAK,EAAI,EAAY,OACxE,EAAc,OAAO,IAAQ,EAAE,IAAM,EAAuB,GAAyB,IACrF,EAAc,OAAO,IAAQ,EAAE,EAAI,MAAQ,EAOjD,OAJI,EAAY,SAAW,IAClB,CAAE,GAAG,EAAa,OAAQ,EAAG,SAAQ,YAAa,EAAiB,KAAM,aAAY,EAGvF,CAAE,GAAG,EAAa,SAAQ,cAAa,aAAY,CAC5D"}
@@ -1,11 +1,4 @@
1
1
  import child_process from 'node:child_process';
2
- /**
3
- * Run an untrusted (submission-derived) command with a timeout. When a judge server delegates
4
- * untrusted execution via `EXERCODE_SANDBOX_USER` (see `sandboxUser.ts`), the whole command,
5
- * including `timeout`, runs as the sandbox user so the timer can signal the sandboxed process; a
6
- * harness-owned watchdog enforces the deadline even if the submission kills its own `timeout`, and
7
- * leftover sandbox processes (e.g. daemonized children) are killed after every run.
8
- */
9
2
  export declare function spawnSyncWithTimeout(command: string, args: readonly string[], options: child_process.SpawnSyncOptionsWithStringEncoding, timeoutSeconds: number): child_process.SpawnSyncReturns<string> & {
10
3
  timeSeconds: number;
11
4
  memoryBytes: number;
@@ -1,2 +1,2 @@
1
- import{TIMEOUT_COMMAND as e,getSandboxUserEnvOverrides as t,killSandboxUserProcesses as n,sandboxUserName as r,startSandboxTimeoutWatchdog as i,wrapCommandWithSandboxUser as a}from"./sandboxUser.js";import o from"node:child_process";import s from"node:os";const c=[s.platform()===`darwin`?`gtime`:`/usr/bin/time`,`--format`,`%e %M`];function l(s,l,u,d){let f=Date.now(),p={...u.env??process.env},m=a([e,d.toFixed(3),...c,s,...l]),h=i(d),g,_;try{g=o.spawnSync(m[0],m.slice(1),{...u,env:{...p,...t(p)}})}finally{_=h.fired(),h.cancel(),r&&n()}let v=Date.now(),y=/(?:^|\n)(\d+\.\d+) (\d+)\s*$/.exec(g.stderr),b=y?g.stderr.slice(0,y.index):g.stderr,x=Number(y?.[1])||(v-f)/1e3,S=Number(y?.[2])*1024||0;return g.status===124||_?{...g,status:0,stderr:b,timeSeconds:d+.001,memoryBytes:S}:{...g,stderr:b,timeSeconds:x,memoryBytes:S}}export{l as spawnSyncWithTimeout};
1
+ import e from"node:child_process";import t from"node:os";const n=[t.platform()===`darwin`?`gtime`:`/usr/bin/time`,`--format`,`%e %M`];function r(t,r,i,a){let o=Date.now(),s=e.spawnSync(`timeout`,[a.toFixed(3),...n,t,...r],i),c=Date.now(),l=/(?:^|\n)(\d+\.\d+) (\d+)\s*$/.exec(s.stderr),u=l?s.stderr.slice(0,l.index):s.stderr,d=Number(l?.[1])||(c-o)/1e3,f=Number(l?.[2])*1024||0;return s.status===124?{...s,status:0,stderr:u,timeSeconds:a+.001,memoryBytes:f}:{...s,stderr:u,timeSeconds:d,memoryBytes:f}}export{r as spawnSyncWithTimeout};
2
2
  //# sourceMappingURL=spawnSyncWithTimeout.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spawnSyncWithTimeout.js","names":[],"sources":["../../src/helpers/spawnSyncWithTimeout.ts"],"sourcesContent":["import child_process from 'node:child_process';\nimport os from 'node:os';\n\nimport {\n getSandboxUserEnvOverrides,\n killSandboxUserProcesses,\n sandboxUserName,\n startSandboxTimeoutWatchdog,\n TIMEOUT_COMMAND,\n wrapCommandWithSandboxUser,\n} from './sandboxUser.js';\n\nconst TIME_COMMAND = [os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time', '--format', '%e %M'] as const;\n\n/**\n * Run an untrusted (submission-derived) command with a timeout. When a judge server delegates\n * untrusted execution via `EXERCODE_SANDBOX_USER` (see `sandboxUser.ts`), the whole command,\n * including `timeout`, runs as the sandbox user so the timer can signal the sandboxed process; a\n * harness-owned watchdog enforces the deadline even if the submission kills its own `timeout`, and\n * leftover sandbox processes (e.g. daemonized children) are killed after every run.\n */\nexport function spawnSyncWithTimeout(\n command: string,\n args: readonly string[],\n options: child_process.SpawnSyncOptionsWithStringEncoding,\n timeoutSeconds: number\n): child_process.SpawnSyncReturns<string> & { timeSeconds: number; memoryBytes: number } {\n const startTimeMilliseconds = Date.now();\n\n const env = { ...(options.env ?? process.env) };\n const wrappedCommand = wrapCommandWithSandboxUser([\n TIMEOUT_COMMAND,\n timeoutSeconds.toFixed(3),\n ...TIME_COMMAND,\n command,\n ...args,\n ]);\n const watchdog = startSandboxTimeoutWatchdog(timeoutSeconds);\n let spawnResult: child_process.SpawnSyncReturns<string>;\n let watchdogFired: boolean;\n try {\n spawnResult = child_process.spawnSync(wrappedCommand[0], wrappedCommand.slice(1), {\n ...options,\n env: { ...env, ...getSandboxUserEnvOverrides(env) },\n });\n } finally {\n // Read the watchdog state before cancelling, then always cancel: a leaked watchdog is detached\n // and would SIGKILL a later request's submission.\n watchdogFired = watchdog.fired();\n watchdog.cancel();\n if (sandboxUserName) killSandboxUserProcesses();\n }\n\n const stopTimeMilliseconds = Date.now();\n\n const match = /(?:^|\\n)(\\d+\\.\\d+) (\\d+)\\s*$/.exec(spawnResult.stderr);\n const stderr = match ? spawnResult.stderr.slice(0, match.index) : spawnResult.stderr;\n const timeSeconds = Number(match?.[1]) || (stopTimeMilliseconds - startTimeMilliseconds) / 1000;\n const memoryBytes = Number(match?.[2]) * 1024 || 0;\n\n // `timeout` reports 124, but a sandboxed submission can kill its own same-UID `timeout` and be\n // stopped by the watchdog instead, which surfaces as a signal-derived status. Both are timeouts:\n // reporting the latter as a runtime error would mislabel a submission that outran its deadline.\n if (spawnResult.status === 124 || watchdogFired) {\n return { ...spawnResult, status: 0, stderr, timeSeconds: timeoutSeconds + 1e-3, memoryBytes };\n }\n\n return { ...spawnResult, stderr, timeSeconds, memoryBytes };\n}\n"],"mappings":"gQAYA,MAAM,EAAe,CAAC,EAAG,SAAS,IAAM,SAAW,QAAU,gBAAiB,WAAY,OAAO,EASjG,SAAgB,EACd,EACA,EACA,EACA,EACuF,CACvF,IAAM,EAAwB,KAAK,IAAI,EAEjC,EAAM,CAAE,GAAI,EAAQ,KAAO,QAAQ,GAAK,EACxC,EAAiB,EAA2B,CAChD,EACA,EAAe,QAAQ,CAAC,EACxB,GAAG,EACH,EACA,GAAG,CACL,CAAC,EACK,EAAW,EAA4B,CAAc,EACvD,EACA,EACJ,GAAI,CACF,EAAc,EAAc,UAAU,EAAe,GAAI,EAAe,MAAM,CAAC,EAAG,CAChF,GAAG,EACH,IAAK,CAAE,GAAG,EAAK,GAAG,EAA2B,CAAG,CAAE,CACpD,CAAC,CACH,QAAU,CAGR,EAAgB,EAAS,MAAM,EAC/B,EAAS,OAAO,EACZ,GAAiB,EAAyB,CAChD,CAEA,IAAM,EAAuB,KAAK,IAAI,EAEhC,EAAQ,+BAA+B,KAAK,EAAY,MAAM,EAC9D,EAAS,EAAQ,EAAY,OAAO,MAAM,EAAG,EAAM,KAAK,EAAI,EAAY,OACxE,EAAc,OAAO,IAAQ,EAAE,IAAM,EAAuB,GAAyB,IACrF,EAAc,OAAO,IAAQ,EAAE,EAAI,MAAQ,EASjD,OAJI,EAAY,SAAW,KAAO,EACzB,CAAE,GAAG,EAAa,OAAQ,EAAG,SAAQ,YAAa,EAAiB,KAAM,aAAY,EAGvF,CAAE,GAAG,EAAa,SAAQ,cAAa,aAAY,CAC5D"}
1
+ {"version":3,"file":"spawnSyncWithTimeout.js","names":[],"sources":["../../src/helpers/spawnSyncWithTimeout.ts"],"sourcesContent":["import child_process from 'node:child_process';\nimport os from 'node:os';\n\nconst TIME_COMMAND = [os.platform() === 'darwin' ? 'gtime' : '/usr/bin/time', '--format', '%e %M'] as const;\n\nexport function spawnSyncWithTimeout(\n command: string,\n args: readonly string[],\n options: child_process.SpawnSyncOptionsWithStringEncoding,\n timeoutSeconds: number\n): child_process.SpawnSyncReturns<string> & { timeSeconds: number; memoryBytes: number } {\n const startTimeMilliseconds = Date.now();\n\n const spawnResult = child_process.spawnSync(\n 'timeout',\n [timeoutSeconds.toFixed(3), ...TIME_COMMAND, command, ...args],\n options\n );\n\n const stopTimeMilliseconds = Date.now();\n\n const match = /(?:^|\\n)(\\d+\\.\\d+) (\\d+)\\s*$/.exec(spawnResult.stderr);\n const stderr = match ? spawnResult.stderr.slice(0, match.index) : spawnResult.stderr;\n const timeSeconds = Number(match?.[1]) || (stopTimeMilliseconds - startTimeMilliseconds) / 1000;\n const memoryBytes = Number(match?.[2]) * 1024 || 0;\n\n // timeout\n if (spawnResult.status === 124) {\n return { ...spawnResult, status: 0, stderr, timeSeconds: timeoutSeconds + 1e-3, memoryBytes };\n }\n\n return { ...spawnResult, stderr, timeSeconds, memoryBytes };\n}\n"],"mappings":"yDAGA,MAAM,EAAe,CAAC,EAAG,SAAS,IAAM,SAAW,QAAU,gBAAiB,WAAY,OAAO,EAEjG,SAAgB,EACd,EACA,EACA,EACA,EACuF,CACvF,IAAM,EAAwB,KAAK,IAAI,EAEjC,EAAc,EAAc,UAChC,UACA,CAAC,EAAe,QAAQ,CAAC,EAAG,GAAG,EAAc,EAAS,GAAG,CAAI,EAC7D,CACF,EAEM,EAAuB,KAAK,IAAI,EAEhC,EAAQ,+BAA+B,KAAK,EAAY,MAAM,EAC9D,EAAS,EAAQ,EAAY,OAAO,MAAM,EAAG,EAAM,KAAK,EAAI,EAAY,OACxE,EAAc,OAAO,IAAQ,EAAE,IAAM,EAAuB,GAAyB,IACrF,EAAc,OAAO,IAAQ,EAAE,EAAI,MAAQ,EAOjD,OAJI,EAAY,SAAW,IAClB,CAAE,GAAG,EAAa,OAAQ,EAAG,SAAQ,YAAa,EAAiB,KAAM,aAAY,EAGvF,CAAE,GAAG,EAAa,SAAQ,cAAa,aAAY,CAC5D"}
@@ -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:http");a=e.__toESM(a,1);function o(e){let t=a.default.createServer((t,n)=>{let a=new URL(t.url??`/`,`http://127.0.0.1`).pathname;a===`/`&&(a=`/index.html`);let o=a.endsWith(`/`)?i.default.join(a,`index.html`):a,s=i.default.join(e,o);if(!c(e,s)){n.statusCode=404,n.end();return}if(r.default.existsSync(s))try{let e=r.default.readFileSync(s);n.writeHead(200,{"Access-Control-Allow-Origin":`*`,Pragma:`no-cache`,"Cache-Control":`no-cache`,"Content-Type":l(o)}),n.end(e)}catch{n.statusCode=500,n.end()}else n.statusCode=404,n.end()});t.listen();let n=t.address();if(!n)throw Error(`server has been unexpectedly closed`);return{[Symbol.asyncDispose]:async()=>{t.closeAllConnections(),await new Promise(e=>{t.close(()=>{e()})})},url:typeof n==`string`?n:`http://127.0.0.1:${n.port}`,port:typeof n==`object`?n.port:void 0}}const s={".css":`text/css`,".html":`text/html`,".js":`text/javascript`,".gif":`image/gif`,".jpg":`image/jpeg`,".png":`image/png`,".svg":`image/svg+xml`};function c(e,i){if(!t.sandboxUserName)return!0;try{return n.isContainedPath(r.default.realpathSync(e),r.default.realpathSync(i))}catch{return!r.default.existsSync(i)}}function l(e){for(let[t,n]of Object.entries(s))if(e.endsWith(t))return n;return`text/plain`}exports.startHttpServer=o;
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("node:fs");t=e.__toESM(t,1);let n=require("node:path");n=e.__toESM(n,1);let r=require("node:http");r=e.__toESM(r,1);function i(e){let i=r.default.createServer((r,i)=>{let a=new URL(r.url??`/`,`http://127.0.0.1`).pathname;a===`/`&&(a=`/index.html`);let s=a.endsWith(`/`)?n.default.join(a,`index.html`):a,c=n.default.join(e,s);if(t.default.existsSync(c))try{let e=t.default.readFileSync(c);i.writeHead(200,{"Access-Control-Allow-Origin":`*`,Pragma:`no-cache`,"Cache-Control":`no-cache`,"Content-Type":o(s)}),i.end(e)}catch{i.statusCode=500,i.end()}else i.statusCode=404,i.end()});i.listen();let a=i.address();if(!a)throw Error(`server has been unexpectedly closed`);return{[Symbol.asyncDispose]:async()=>{i.closeAllConnections(),await new Promise(e=>{i.close(()=>{e()})})},url:typeof a==`string`?a:`http://127.0.0.1:${a.port}`,port:typeof a==`object`?a.port:void 0}}const a={".css":`text/css`,".html":`text/html`,".js":`text/javascript`,".gif":`image/gif`,".jpg":`image/jpeg`,".png":`image/png`,".svg":`image/svg+xml`};function o(e){for(let[t,n]of Object.entries(a))if(e.endsWith(t))return n;return`text/plain`}exports.startHttpServer=i;
2
2
  //# sourceMappingURL=startHttpServer.cjs.map