@exercode/problem-utils 2.4.0 → 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,14 +35,14 @@ A standard stdin/stdout problem must NOT commit a `judge.ts` or `debug.ts` that
35
35
 
36
36
  A problem keeps its test cases under `test_cases/`. A test case id is the shared name of the following entries, and each entry is optional:
37
37
 
38
- | Entry | Meaning |
39
- | -------------- | --------------------------------------------------------------------------------------------------------------------------------- |
40
- | `<id>.in` | Standard input. Omit it (or leave it empty) when the program reads nothing. |
41
- | `<id>.out` | Expected standard output. |
42
- | `<id>.fin/` | Files copied into the working directory before the run (input files). |
43
- | `<id>.fout/` | Expected output files, compared with the files of the same relative paths in the working directory. |
44
- | `_shared.fin/` | Files copied into the working directory before every test case. |
45
- | `<id>.json` | Configuration for a custom `judge.ts` that reads it itself; the presets ignore it, and it does not create a test case on its own. |
38
+ | Entry | Meaning |
39
+ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
40
+ | `<id>.in` | Standard input. Omit it (or leave it empty) when the program reads nothing. |
41
+ | `<id>.out` | Expected standard output. |
42
+ | `<id>.fin/` | Files copied into the working directory before the run (input files). |
43
+ | `<id>.fout/` | Expected output files, compared with the files of the same relative paths in the working directory. |
44
+ | `_shared.fin/` | Files copied into the working directory before every test case. |
45
+ | `<id>.json` | Configuration for a custom `judge.ts` that reads it itself; the presets ignore it (the Judge server lists it as a test case of the custom judge). |
46
46
 
47
47
  A test case whose id contains `example` (the judge server's rule, e.g. `example_1` or `01_example_small`) is an example shown to learners; every other case is hidden.
48
48
 
@@ -50,7 +50,7 @@ Standard output and text files are compared as space-separated tokens: consecuti
50
50
 
51
51
  How a missing expectation is treated depends on the harness:
52
52
 
53
- - `stdioJudgePreset` (the default for problems without `judge.ts`) requires `<id>.out` or a non-empty `<id>.fout/` for every test case, so a standard problem cannot accept a run without checking it. A problem whose `problem.md` declares `requiredOutputFilePaths`, code rules (`requiredRegExpsInCode` etc.), `requiredSubmissionFilePaths` or `isManualScoringRequired` is exempt, because it is judged by those instead.
53
+ - `stdioJudgePreset` (the default for problems without `judge.ts`) requires `<id>.out` or a non-empty `<id>.fout/` for every test case, so a standard problem cannot accept a run without checking it. A problem whose `problem.md` declares `requiredOutputFilePaths` or `isManualScoringRequired` is exempt, because every test case is judged by those instead; code rules (`requiredRegExpsInCode` etc.) and `requiredSubmissionFilePaths` check the submission once, in addition to the output comparison, and do not exempt.
54
54
  - `commandJudgePreset` without a `test` option checks whatever expectations exist, and a test case with neither only has to run within the limits. A `test` option replaces that comparison; it receives `testCase.output`, `testCase.fileOutputPath` and `cwd` and can call the exported `judgeAgainstExpectations` (or `compareStdoutAsSpaceSeparatedTokens` and `compareExpectedOutputFiles`). A custom `readTestCases` may return any test case type with `id` (plus optional `input` and `fileInputPath`); the default verdict judges any case that exposes a string `output` or `fileOutputPath`, which the default reader's `CommandTestCase` does.
55
55
  - `guiCommandJudgePreset` passes the expectations to the problem's `test`, which decides everything.
56
56
  - `llmJudgePreset` runs no program, so it copies no `.fin/`; it hands `<id>.in` as the prompt input and the whole entry (including `fileOutputPath`) to the problem's `test`.
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../types/problem.cjs");let n=require("node:fs");n=e.__toESM(n,1);let r=require("node:path");r=e.__toESM(r,1);let i=require("front-matter");i=e.__toESM(i,1);function a(e){return e.isManualScoringRequired===!0||(e.requiredRegExpsInCode?.length??0)>0||(e.forbiddenRegExpsInCode?.length??0)>0||(e.forbiddenTextsInCode?.length??0)>0||(e.requiredSubmissionFilePaths?.length??0)>0}async function o(e){for(let a of await n.default.promises.readdir(e,{withFileTypes:!0})){if(!a.isFile()||!(a.name===`problem.md`||a.name.endsWith(`.problem.md`)))continue;let e=await n.default.promises.readFile(r.default.join(a.parentPath,a.name),`utf8`),{attributes:o}=(0,i.default)(e);return t.problemMarkdownFrontMatterSchema.parse(o)}throw Error(`problem markdown not found: ${e}`)}exports.judgesWithoutTestCases=a,exports.readProblemMarkdownFrontMatter=o;
1
+ "use strict";const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../types/problem.cjs");let n=require("node:fs");n=e.__toESM(n,1);let r=require("node:path");r=e.__toESM(r,1);let i=require("front-matter");i=e.__toESM(i,1);function a(e){return e.isManualScoringRequired===!0||(e.requiredRegExpsInCode?.length??0)>0||(e.forbiddenRegExpsInCode?.length??0)>0||(e.forbiddenTextsInCode?.length??0)>0||(e.requiredSubmissionFilePaths?.length??0)>0}function o(e){return e.isManualScoringRequired===!0||(e.requiredOutputFilePaths?.length??0)>0}async function s(e){for(let a of await n.default.promises.readdir(e,{withFileTypes:!0})){if(!a.isFile()||!(a.name===`problem.md`||a.name.endsWith(`.problem.md`)))continue;let e=await n.default.promises.readFile(r.default.join(a.parentPath,a.name),`utf8`),{attributes:o}=(0,i.default)(e);return t.problemMarkdownFrontMatterSchema.parse(o)}throw Error(`problem markdown not found: ${e}`)}exports.judgesTestCasesWithoutExpectations=o,exports.judgesWithoutTestCases=a,exports.readProblemMarkdownFrontMatter=s;
2
2
  //# sourceMappingURL=readProblemMarkdownFrontMatter.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"readProblemMarkdownFrontMatter.cjs","names":["fs","path","parseFrontMatter","problemMarkdownFrontMatterSchema"],"sources":["../../src/helpers/readProblemMarkdownFrontMatter.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport parseFrontMatter from 'front-matter';\n\nimport type { ProblemMarkdownFrontMatter } from '../types/problem.js';\nimport { problemMarkdownFrontMatterSchema } from '../types/problem.js';\n\n/**\n * Whether a standard stdio problem is judgeable without test cases: static-analysis rules still\n * judge the submitted code, and manual scoring intentionally accepts every submission.\n */\nexport function judgesWithoutTestCases(frontMatter: ProblemMarkdownFrontMatter): boolean {\n return (\n frontMatter.isManualScoringRequired === true ||\n (frontMatter.requiredRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenTextsInCode?.length ?? 0) > 0 ||\n (frontMatter.requiredSubmissionFilePaths?.length ?? 0) > 0\n );\n}\n\nexport async function readProblemMarkdownFrontMatter(problemDir: string): Promise<ProblemMarkdownFrontMatter> {\n for (const dirent of await fs.promises.readdir(problemDir, { withFileTypes: true })) {\n if (!dirent.isFile()) continue;\n if (!(dirent.name === 'problem.md' || dirent.name.endsWith('.problem.md'))) continue;\n\n const markdown = await fs.promises.readFile(path.join(dirent.parentPath, dirent.name), 'utf8');\n\n const { attributes } = (parseFrontMatter as unknown as (markdown: string) => { attributes: unknown })(markdown);\n\n return problemMarkdownFrontMatterSchema.parse(attributes);\n }\n\n throw new Error(`problem markdown not found: ${problemDir}`);\n}\n"],"mappings":"yOAYA,SAAgB,EAAuB,EAAkD,CACvF,OACE,EAAY,0BAA4B,KACvC,EAAY,uBAAuB,QAAU,GAAK,IAClD,EAAY,wBAAwB,QAAU,GAAK,IACnD,EAAY,sBAAsB,QAAU,GAAK,IACjD,EAAY,6BAA6B,QAAU,GAAK,CAE7D,CAEA,eAAsB,EAA+B,EAAyD,CAC5G,IAAK,IAAM,KAAU,MAAMA,EAAAA,QAAG,SAAS,QAAQ,EAAY,CAAE,cAAe,EAAK,CAAC,EAAG,CAEnF,GADI,CAAC,EAAO,OAAO,GACf,EAAE,EAAO,OAAS,cAAgB,EAAO,KAAK,SAAS,aAAa,GAAI,SAE5E,IAAM,EAAW,MAAMA,EAAAA,QAAG,SAAS,SAASC,EAAAA,QAAK,KAAK,EAAO,WAAY,EAAO,IAAI,EAAG,MAAM,EAEvF,CAAE,eAAA,EAAgBC,EAAAA,QAAAA,CAA8E,CAAQ,EAE9G,OAAOC,EAAAA,iCAAiC,MAAM,CAAU,CAC1D,CAEA,MAAU,MAAM,+BAA+B,GAAY,CAC7D"}
1
+ {"version":3,"file":"readProblemMarkdownFrontMatter.cjs","names":["fs","path","parseFrontMatter","problemMarkdownFrontMatterSchema"],"sources":["../../src/helpers/readProblemMarkdownFrontMatter.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport parseFrontMatter from 'front-matter';\n\nimport type { ProblemMarkdownFrontMatter } from '../types/problem.js';\nimport { problemMarkdownFrontMatterSchema } from '../types/problem.js';\n\n/**\n * Whether a standard stdio problem is judgeable without test cases: static-analysis rules still\n * judge the submitted code, and manual scoring intentionally accepts every submission.\n */\nexport function judgesWithoutTestCases(frontMatter: ProblemMarkdownFrontMatter): boolean {\n return (\n frontMatter.isManualScoringRequired === true ||\n (frontMatter.requiredRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenTextsInCode?.length ?? 0) > 0 ||\n (frontMatter.requiredSubmissionFilePaths?.length ?? 0) > 0\n );\n}\n\n/**\n * Whether the front matter judges every test case without an expected output: manual scoring\n * accepts every run, and required output files are checked by their presence after each run.\n * Code rules and required submission files do not count because they check the submission once,\n * in addition to the output comparison.\n */\nexport function judgesTestCasesWithoutExpectations(frontMatter: ProblemMarkdownFrontMatter): boolean {\n return frontMatter.isManualScoringRequired === true || (frontMatter.requiredOutputFilePaths?.length ?? 0) > 0;\n}\n\nexport async function readProblemMarkdownFrontMatter(problemDir: string): Promise<ProblemMarkdownFrontMatter> {\n for (const dirent of await fs.promises.readdir(problemDir, { withFileTypes: true })) {\n if (!dirent.isFile()) continue;\n if (!(dirent.name === 'problem.md' || dirent.name.endsWith('.problem.md'))) continue;\n\n const markdown = await fs.promises.readFile(path.join(dirent.parentPath, dirent.name), 'utf8');\n\n const { attributes } = (parseFrontMatter as unknown as (markdown: string) => { attributes: unknown })(markdown);\n\n return problemMarkdownFrontMatterSchema.parse(attributes);\n }\n\n throw new Error(`problem markdown not found: ${problemDir}`);\n}\n"],"mappings":"yOAYA,SAAgB,EAAuB,EAAkD,CACvF,OACE,EAAY,0BAA4B,KACvC,EAAY,uBAAuB,QAAU,GAAK,IAClD,EAAY,wBAAwB,QAAU,GAAK,IACnD,EAAY,sBAAsB,QAAU,GAAK,IACjD,EAAY,6BAA6B,QAAU,GAAK,CAE7D,CAQA,SAAgB,EAAmC,EAAkD,CACnG,OAAO,EAAY,0BAA4B,KAAS,EAAY,yBAAyB,QAAU,GAAK,CAC9G,CAEA,eAAsB,EAA+B,EAAyD,CAC5G,IAAK,IAAM,KAAU,MAAMA,EAAAA,QAAG,SAAS,QAAQ,EAAY,CAAE,cAAe,EAAK,CAAC,EAAG,CAEnF,GADI,CAAC,EAAO,OAAO,GACf,EAAE,EAAO,OAAS,cAAgB,EAAO,KAAK,SAAS,aAAa,GAAI,SAE5E,IAAM,EAAW,MAAMA,EAAAA,QAAG,SAAS,SAASC,EAAAA,QAAK,KAAK,EAAO,WAAY,EAAO,IAAI,EAAG,MAAM,EAEvF,CAAE,eAAA,EAAgBC,EAAAA,QAAAA,CAA8E,CAAQ,EAE9G,OAAOC,EAAAA,iCAAiC,MAAM,CAAU,CAC1D,CAEA,MAAU,MAAM,+BAA+B,GAAY,CAC7D"}
@@ -4,4 +4,11 @@ import type { ProblemMarkdownFrontMatter } from '../types/problem.js';
4
4
  * judge the submitted code, and manual scoring intentionally accepts every submission.
5
5
  */
6
6
  export declare function judgesWithoutTestCases(frontMatter: ProblemMarkdownFrontMatter): boolean;
7
+ /**
8
+ * Whether the front matter judges every test case without an expected output: manual scoring
9
+ * accepts every run, and required output files are checked by their presence after each run.
10
+ * Code rules and required submission files do not count because they check the submission once,
11
+ * in addition to the output comparison.
12
+ */
13
+ export declare function judgesTestCasesWithoutExpectations(frontMatter: ProblemMarkdownFrontMatter): boolean;
7
14
  export declare function readProblemMarkdownFrontMatter(problemDir: string): Promise<ProblemMarkdownFrontMatter>;
@@ -1,2 +1,2 @@
1
- import{problemMarkdownFrontMatterSchema as e}from"../types/problem.js";import t from"node:fs";import n from"node:path";import r from"front-matter";function i(e){return e.isManualScoringRequired===!0||(e.requiredRegExpsInCode?.length??0)>0||(e.forbiddenRegExpsInCode?.length??0)>0||(e.forbiddenTextsInCode?.length??0)>0||(e.requiredSubmissionFilePaths?.length??0)>0}async function a(i){for(let a of await t.promises.readdir(i,{withFileTypes:!0})){if(!a.isFile()||!(a.name===`problem.md`||a.name.endsWith(`.problem.md`)))continue;let i=await t.promises.readFile(n.join(a.parentPath,a.name),`utf8`),{attributes:o}=r(i);return e.parse(o)}throw Error(`problem markdown not found: ${i}`)}export{i as judgesWithoutTestCases,a as readProblemMarkdownFrontMatter};
1
+ import{problemMarkdownFrontMatterSchema as e}from"../types/problem.js";import t from"node:fs";import n from"node:path";import r from"front-matter";function i(e){return e.isManualScoringRequired===!0||(e.requiredRegExpsInCode?.length??0)>0||(e.forbiddenRegExpsInCode?.length??0)>0||(e.forbiddenTextsInCode?.length??0)>0||(e.requiredSubmissionFilePaths?.length??0)>0}function a(e){return e.isManualScoringRequired===!0||(e.requiredOutputFilePaths?.length??0)>0}async function o(i){for(let a of await t.promises.readdir(i,{withFileTypes:!0})){if(!a.isFile()||!(a.name===`problem.md`||a.name.endsWith(`.problem.md`)))continue;let i=await t.promises.readFile(n.join(a.parentPath,a.name),`utf8`),{attributes:o}=r(i);return e.parse(o)}throw Error(`problem markdown not found: ${i}`)}export{a as judgesTestCasesWithoutExpectations,i as judgesWithoutTestCases,o as readProblemMarkdownFrontMatter};
2
2
  //# sourceMappingURL=readProblemMarkdownFrontMatter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"readProblemMarkdownFrontMatter.js","names":[],"sources":["../../src/helpers/readProblemMarkdownFrontMatter.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport parseFrontMatter from 'front-matter';\n\nimport type { ProblemMarkdownFrontMatter } from '../types/problem.js';\nimport { problemMarkdownFrontMatterSchema } from '../types/problem.js';\n\n/**\n * Whether a standard stdio problem is judgeable without test cases: static-analysis rules still\n * judge the submitted code, and manual scoring intentionally accepts every submission.\n */\nexport function judgesWithoutTestCases(frontMatter: ProblemMarkdownFrontMatter): boolean {\n return (\n frontMatter.isManualScoringRequired === true ||\n (frontMatter.requiredRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenTextsInCode?.length ?? 0) > 0 ||\n (frontMatter.requiredSubmissionFilePaths?.length ?? 0) > 0\n );\n}\n\nexport async function readProblemMarkdownFrontMatter(problemDir: string): Promise<ProblemMarkdownFrontMatter> {\n for (const dirent of await fs.promises.readdir(problemDir, { withFileTypes: true })) {\n if (!dirent.isFile()) continue;\n if (!(dirent.name === 'problem.md' || dirent.name.endsWith('.problem.md'))) continue;\n\n const markdown = await fs.promises.readFile(path.join(dirent.parentPath, dirent.name), 'utf8');\n\n const { attributes } = (parseFrontMatter as unknown as (markdown: string) => { attributes: unknown })(markdown);\n\n return problemMarkdownFrontMatterSchema.parse(attributes);\n }\n\n throw new Error(`problem markdown not found: ${problemDir}`);\n}\n"],"mappings":"mJAYA,SAAgB,EAAuB,EAAkD,CACvF,OACE,EAAY,0BAA4B,KACvC,EAAY,uBAAuB,QAAU,GAAK,IAClD,EAAY,wBAAwB,QAAU,GAAK,IACnD,EAAY,sBAAsB,QAAU,GAAK,IACjD,EAAY,6BAA6B,QAAU,GAAK,CAE7D,CAEA,eAAsB,EAA+B,EAAyD,CAC5G,IAAK,IAAM,KAAU,MAAM,EAAG,SAAS,QAAQ,EAAY,CAAE,cAAe,EAAK,CAAC,EAAG,CAEnF,GADI,CAAC,EAAO,OAAO,GACf,EAAE,EAAO,OAAS,cAAgB,EAAO,KAAK,SAAS,aAAa,GAAI,SAE5E,IAAM,EAAW,MAAM,EAAG,SAAS,SAAS,EAAK,KAAK,EAAO,WAAY,EAAO,IAAI,EAAG,MAAM,EAEvF,CAAE,cAAgB,EAA8E,CAAQ,EAE9G,OAAO,EAAiC,MAAM,CAAU,CAC1D,CAEA,MAAU,MAAM,+BAA+B,GAAY,CAC7D"}
1
+ {"version":3,"file":"readProblemMarkdownFrontMatter.js","names":[],"sources":["../../src/helpers/readProblemMarkdownFrontMatter.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport parseFrontMatter from 'front-matter';\n\nimport type { ProblemMarkdownFrontMatter } from '../types/problem.js';\nimport { problemMarkdownFrontMatterSchema } from '../types/problem.js';\n\n/**\n * Whether a standard stdio problem is judgeable without test cases: static-analysis rules still\n * judge the submitted code, and manual scoring intentionally accepts every submission.\n */\nexport function judgesWithoutTestCases(frontMatter: ProblemMarkdownFrontMatter): boolean {\n return (\n frontMatter.isManualScoringRequired === true ||\n (frontMatter.requiredRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenRegExpsInCode?.length ?? 0) > 0 ||\n (frontMatter.forbiddenTextsInCode?.length ?? 0) > 0 ||\n (frontMatter.requiredSubmissionFilePaths?.length ?? 0) > 0\n );\n}\n\n/**\n * Whether the front matter judges every test case without an expected output: manual scoring\n * accepts every run, and required output files are checked by their presence after each run.\n * Code rules and required submission files do not count because they check the submission once,\n * in addition to the output comparison.\n */\nexport function judgesTestCasesWithoutExpectations(frontMatter: ProblemMarkdownFrontMatter): boolean {\n return frontMatter.isManualScoringRequired === true || (frontMatter.requiredOutputFilePaths?.length ?? 0) > 0;\n}\n\nexport async function readProblemMarkdownFrontMatter(problemDir: string): Promise<ProblemMarkdownFrontMatter> {\n for (const dirent of await fs.promises.readdir(problemDir, { withFileTypes: true })) {\n if (!dirent.isFile()) continue;\n if (!(dirent.name === 'problem.md' || dirent.name.endsWith('.problem.md'))) continue;\n\n const markdown = await fs.promises.readFile(path.join(dirent.parentPath, dirent.name), 'utf8');\n\n const { attributes } = (parseFrontMatter as unknown as (markdown: string) => { attributes: unknown })(markdown);\n\n return problemMarkdownFrontMatterSchema.parse(attributes);\n }\n\n throw new Error(`problem markdown not found: ${problemDir}`);\n}\n"],"mappings":"mJAYA,SAAgB,EAAuB,EAAkD,CACvF,OACE,EAAY,0BAA4B,KACvC,EAAY,uBAAuB,QAAU,GAAK,IAClD,EAAY,wBAAwB,QAAU,GAAK,IACnD,EAAY,sBAAsB,QAAU,GAAK,IACjD,EAAY,6BAA6B,QAAU,GAAK,CAE7D,CAQA,SAAgB,EAAmC,EAAkD,CACnG,OAAO,EAAY,0BAA4B,KAAS,EAAY,yBAAyB,QAAU,GAAK,CAC9G,CAEA,eAAsB,EAA+B,EAAyD,CAC5G,IAAK,IAAM,KAAU,MAAM,EAAG,SAAS,QAAQ,EAAY,CAAE,cAAe,EAAK,CAAC,EAAG,CAEnF,GADI,CAAC,EAAO,OAAO,GACf,EAAE,EAAO,OAAS,cAAgB,EAAO,KAAK,SAAS,aAAa,GAAI,SAE5E,IAAM,EAAW,MAAM,EAAG,SAAS,SAAS,EAAK,KAAK,EAAO,WAAY,EAAO,IAAI,EAAG,MAAM,EAEvF,CAAE,cAAgB,EAA8E,CAAQ,EAE9G,OAAO,EAAiC,MAAM,CAAU,CAC1D,CAEA,MAAU,MAAM,+BAA+B,GAAY,CAC7D"}
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../helpers/printTestCaseResult.cjs"),n=require("../helpers/sandboxUser.cjs"),r=require("../helpers/readOutputFiles.cjs"),i=require("../helpers/compareExpectedOutputFiles.cjs"),a=require("../helpers/parseArgs.cjs"),o=require("../helpers/readTestCases.cjs"),s=require("../types/decisionCode.cjs"),c=require("../helpers/cleanWorkingDirectory.cjs"),l=require("../helpers/copyTestCaseFileInput.cjs"),u=require("../helpers/findEntryPointFile.cjs"),d=require("../helpers/findLanguageDefinitionByPath.cjs"),f=require("../helpers/judgeByStaticAnalysis.cjs"),p=require("../helpers/temporaryProblemDirCopy.cjs"),m=require("../helpers/readProblemMarkdownFrontMatter.cjs"),h=require("../helpers/spawnSyncWithTimeout.cjs");let g=require("node:fs");g=e.__toESM(g,1);let _=require("node:path");_=e.__toESM(_,1);let v=require("zod");const y=5e4,b=/example/,x=v.z.object({language:v.z.union([v.z.string(),v.z.array(v.z.string())]).optional()}),S=x.extend({stdin:v.z.string().optional()});async function C(e){let p=a.parseArgs(process.argv);if(!p.cwd)throw Error(`cwd argument required`);let g=x.parse(p.params);n.makeAccessibleToSandboxUser(p.cwd);let v=await m.readProblemMarkdownFrontMatter(e),b=await o.readTestCases(_.default.join(e,`test_cases`)),S=await f.judgeByStaticAnalysis(p.cwd,v);if(S){t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,...S});return}if(!m.judgesWithoutTestCases(v)&&!v.requiredOutputFilePaths?.length){for(let e of b)if(e.output===void 0&&!await w(e.fileOutputPath))throw Error(`test case ${e.id} needs an expected output (${e.id}.out or a non-empty ${e.id}.fout/)`)}let C=await u.findEntryPointFile(p.cwd,g.language);if(!C){t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${g.language?`: language: ${g.language}`:``}`});return}let T=d.findLanguageDefinitionByPath(C);if(!T){t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.DecisionCode.WRONG_ANSWER,stderr:`unsupported language`});return}let E={...process.env,CI:``,FORCE_COLOR:`0`},D;if(T.prebuild)try{await T.prebuild(p.cwd),D=await u.findEntryPointFile(p.cwd,g.language)}catch(e){console.error(`prebuild error`,e),t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let O=D??C;if(T.buildCommand)try{let e=T.buildCommand(O),n=h.spawnSyncWithTimeout(e[0],e.slice(1),{cwd:p.cwd,encoding:`utf8`,env:E},10),r=s.DecisionCode.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>y||n.stderr.length>y)&&(r=s.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.DecisionCode.BUILD_ERROR,r!==s.DecisionCode.ACCEPTED){t.printTestCaseResult({testCaseId:b[0]?.id??`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,y)||void 0,stderr:n.stderr.slice(0,y)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(e){console.error(`build error`,e),t.printTestCaseResult({testCaseId:b[0]?.id??`build`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let k=await c.snapshotWorkingDirectory(p.cwd);b.length===0&&t.printTestCaseResult({testCaseId:`default`,decisionCode:s.DecisionCode.ACCEPTED});for(let e of b){b.shared?.fileInputPath&&await l.copyTestCaseFileInput(b.shared.fileInputPath,p.cwd),e.fileInputPath&&await l.copyTestCaseFileInput(e.fileInputPath,p.cwd);let n=typeof v.timeLimitMs==`number`?v.timeLimitMs/1e3:2,a=T.command(O),o=h.spawnSyncWithTimeout(a[0],a.slice(1),{cwd:p.cwd,encoding:`utf8`,input:e.input,env:E},n),u=await r.readOutputFiles(p.cwd,v.requiredOutputFilePaths??[]),d=s.DecisionCode.ACCEPTED,f;if(o.status!==0)d=s.DecisionCode.RUNTIME_ERROR;else if(o.timeSeconds>n)d=s.DecisionCode.TIME_LIMIT_EXCEEDED;else if(o.memoryBytes>(v.memoryLimitByte??1/0))d=s.DecisionCode.MEMORY_LIMIT_EXCEEDED;else if(o.stdout.length>y||o.stderr.length>y)d=s.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;else if(u.length<(v.requiredOutputFilePaths?.length??0))d=s.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;else try{let t=await i.judgeAgainstExpectations({stdout:o.stdout,expectedStdout:e.output,fileOutputPath:e.fileOutputPath,cwd:p.cwd,outputFiles:u});t.matches||(d=s.DecisionCode.WRONG_ANSWER),u=t.outputFiles}catch(e){d=s.DecisionCode.RUNTIME_ERROR,f=e instanceof Error?e.message:String(e)}if(t.printTestCaseResult({testCaseId:e.id,decisionCode:d,exitStatus:o.status??void 0,stdin:e.input,stdout:o.stdout.slice(0,y)||void 0,stderr:(f??o.stderr).slice(0,y)||void 0,timeSeconds:o.timeSeconds,memoryBytes:o.memoryBytes,outputFiles:u.length>0?u:void 0}),await c.cleanWorkingDirectory(p.cwd,k),d!==s.DecisionCode.ACCEPTED)break}}async function w(e){return e!==void 0&&(await g.default.promises.readdir(e,{withFileTypes:!0,recursive:!0})).some(e=>e.isFile())}async function T(e){let t=a.parseArgs(process.argv);if(!t.cwd)throw Error(`cwd argument required`);let r=S.parse(t.params),i,o=()=>{i!==void 0&&p.forciblyRemoveDirectorySync(i),process.exit(1)};process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{let a=await p.copyProblemDirToTemporaryRoot(t.cwd,{onTempRootCreated:e=>i=e});n.makeTraversableBySandboxUser(a.tempRoot,_.default.dirname(a.copiedProblemDir)),await E(e,a.copiedProblemDir,r)}finally{i!==void 0&&await p.forciblyRemoveDirectory(i),process.off(`SIGINT`,o),process.off(`SIGTERM`,o)}}async function E(e,i,a){n.makeAccessibleToSandboxUser(i);let c=await m.readProblemMarkdownFrontMatter(e),f=await u.findEntryPointFile(i,a.language);if(!f){t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:s.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${a.language?`: language: ${a.language}`:``}`});return}let p=d.findLanguageDefinitionByPath(f);if(!p){t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:s.DecisionCode.WRONG_ANSWER,stderr:`unsupported language`});return}let g={...process.env,CI:``,FORCE_COLOR:`0`},v;if(p.prebuild)try{await p.prebuild(i),v=await u.findEntryPointFile(i,a.language)}catch(e){console.error(`prebuild error`,e),t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let x=v??f;if(p.buildCommand)try{let e=p.buildCommand(x),n=h.spawnSyncWithTimeout(e[0],e.slice(1),{cwd:i,encoding:`utf8`,env:g},10),r=s.DecisionCode.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>y||n.stderr.length>y)&&(r=s.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.DecisionCode.BUILD_ERROR,r!==s.DecisionCode.ACCEPTED){t.printTestCaseResult({testCaseId:`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,y)||void 0,stderr:n.stderr.slice(0,y)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(e){console.error(`build error`,e),t.printTestCaseResult({testCaseId:`build`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let S=await o.readTestCases(_.default.join(e,`test_cases`));S.shared?.fileInputPath&&await l.copyTestCaseFileInput(S.shared.fileInputPath,i);let C=S.find(e=>b.test(e.id)&&e.fileInputPath)?.fileInputPath;C?await l.copyTestCaseFileInput(C,i):S.some(e=>e.fileInputPath)&&console.error(`debug: no example test case has input files, so the program runs without them`);let w=Math.max(10,(c.timeLimitMs??0)/1e3),T=p.command(x),E=h.spawnSyncWithTimeout(T[0],T.slice(1),{cwd:i,encoding:`utf8`,input:a.stdin,env:g},w),D=await r.readOutputFiles(i,c.requiredOutputFilePaths??[]),O=s.DecisionCode.ACCEPTED;E.status===0?E.timeSeconds>w?O=s.DecisionCode.TIME_LIMIT_EXCEEDED:E.memoryBytes>(c.memoryLimitByte??1/0)?O=s.DecisionCode.MEMORY_LIMIT_EXCEEDED:E.stdout.length>y||E.stderr.length>y?O=s.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED:D.length<(c.requiredOutputFilePaths?.length??0)&&(O=s.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR):O=s.DecisionCode.RUNTIME_ERROR,t.printTestCaseResult({testCaseId:`debug`,decisionCode:O,exitStatus:E.status??void 0,stdin:a.stdin,stdout:E.stdout.slice(0,y)||void 0,stderr:E.stderr.slice(0,y)||void 0,timeSeconds:E.timeSeconds,memoryBytes:E.memoryBytes,outputFiles:D.length>0?D:void 0})}exports.stdioDebugPreset=T,exports.stdioJudgePreset=C;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("../_virtual/_rolldown/runtime.cjs"),t=require("../helpers/printTestCaseResult.cjs"),n=require("../helpers/sandboxUser.cjs"),r=require("../helpers/readOutputFiles.cjs"),i=require("../helpers/compareExpectedOutputFiles.cjs"),a=require("../helpers/parseArgs.cjs"),o=require("../helpers/readTestCases.cjs"),s=require("../types/decisionCode.cjs"),c=require("../helpers/cleanWorkingDirectory.cjs"),l=require("../helpers/copyTestCaseFileInput.cjs"),u=require("../helpers/findEntryPointFile.cjs"),d=require("../helpers/findLanguageDefinitionByPath.cjs"),f=require("../helpers/judgeByStaticAnalysis.cjs"),p=require("../helpers/temporaryProblemDirCopy.cjs"),m=require("../helpers/readProblemMarkdownFrontMatter.cjs"),h=require("../helpers/spawnSyncWithTimeout.cjs");let g=require("node:fs");g=e.__toESM(g,1);let _=require("node:path");_=e.__toESM(_,1);let v=require("zod");const y=5e4,b=/example/,x=v.z.object({language:v.z.union([v.z.string(),v.z.array(v.z.string())]).optional()}),S=x.extend({stdin:v.z.string().optional()});async function C(e){let p=a.parseArgs(process.argv);if(!p.cwd)throw Error(`cwd argument required`);let g=x.parse(p.params);n.makeAccessibleToSandboxUser(p.cwd);let v=await m.readProblemMarkdownFrontMatter(e),b=await o.readTestCases(_.default.join(e,`test_cases`));if(!m.judgesTestCasesWithoutExpectations(v)){for(let e of b)if(e.output===void 0&&!await w(e.fileOutputPath))throw Error(`test case ${e.id} needs an expected output (${e.id}.out or a non-empty ${e.id}.fout/)`)}let S=await f.judgeByStaticAnalysis(p.cwd,v);if(S){t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,...S});return}let C=await u.findEntryPointFile(p.cwd,g.language);if(!C){t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${g.language?`: language: ${g.language}`:``}`});return}let T=d.findLanguageDefinitionByPath(C);if(!T){t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.DecisionCode.WRONG_ANSWER,stderr:`unsupported language`});return}let E={...process.env,CI:``,FORCE_COLOR:`0`},D;if(T.prebuild)try{await T.prebuild(p.cwd),D=await u.findEntryPointFile(p.cwd,g.language)}catch(e){console.error(`prebuild error`,e),t.printTestCaseResult({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let O=D??C;if(T.buildCommand)try{let e=T.buildCommand(O),n=h.spawnSyncWithTimeout(e[0],e.slice(1),{cwd:p.cwd,encoding:`utf8`,env:E},10),r=s.DecisionCode.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>y||n.stderr.length>y)&&(r=s.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.DecisionCode.BUILD_ERROR,r!==s.DecisionCode.ACCEPTED){t.printTestCaseResult({testCaseId:b[0]?.id??`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,y)||void 0,stderr:n.stderr.slice(0,y)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(e){console.error(`build error`,e),t.printTestCaseResult({testCaseId:b[0]?.id??`build`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let k=await c.snapshotWorkingDirectory(p.cwd);b.length===0&&t.printTestCaseResult({testCaseId:`default`,decisionCode:s.DecisionCode.ACCEPTED});for(let e of b){b.shared?.fileInputPath&&await l.copyTestCaseFileInput(b.shared.fileInputPath,p.cwd),e.fileInputPath&&await l.copyTestCaseFileInput(e.fileInputPath,p.cwd);let n=typeof v.timeLimitMs==`number`?v.timeLimitMs/1e3:2,a=T.command(O),o=h.spawnSyncWithTimeout(a[0],a.slice(1),{cwd:p.cwd,encoding:`utf8`,input:e.input,env:E},n),u=await r.readOutputFiles(p.cwd,v.requiredOutputFilePaths??[]),d=s.DecisionCode.ACCEPTED,f;if(o.status!==0)d=s.DecisionCode.RUNTIME_ERROR;else if(o.timeSeconds>n)d=s.DecisionCode.TIME_LIMIT_EXCEEDED;else if(o.memoryBytes>(v.memoryLimitByte??1/0))d=s.DecisionCode.MEMORY_LIMIT_EXCEEDED;else if(o.stdout.length>y||o.stderr.length>y)d=s.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;else if(u.length<(v.requiredOutputFilePaths?.length??0))d=s.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;else try{let t=await i.judgeAgainstExpectations({stdout:o.stdout,expectedStdout:e.output,fileOutputPath:e.fileOutputPath,cwd:p.cwd,outputFiles:u});t.matches||(d=s.DecisionCode.WRONG_ANSWER),u=t.outputFiles}catch(e){d=s.DecisionCode.RUNTIME_ERROR,f=e instanceof Error?e.message:String(e)}if(t.printTestCaseResult({testCaseId:e.id,decisionCode:d,exitStatus:o.status??void 0,stdin:e.input,stdout:o.stdout.slice(0,y)||void 0,stderr:(f??o.stderr).slice(0,y)||void 0,timeSeconds:o.timeSeconds,memoryBytes:o.memoryBytes,outputFiles:u.length>0?u:void 0}),await c.cleanWorkingDirectory(p.cwd,k),d!==s.DecisionCode.ACCEPTED)break}}async function w(e){return e!==void 0&&(await g.default.promises.readdir(e,{withFileTypes:!0,recursive:!0})).some(e=>e.isFile())}async function T(e){let t=a.parseArgs(process.argv);if(!t.cwd)throw Error(`cwd argument required`);let r=S.parse(t.params),i,o=()=>{i!==void 0&&p.forciblyRemoveDirectorySync(i),process.exit(1)};process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{let a=await p.copyProblemDirToTemporaryRoot(t.cwd,{onTempRootCreated:e=>i=e});n.makeTraversableBySandboxUser(a.tempRoot,_.default.dirname(a.copiedProblemDir)),await E(e,a.copiedProblemDir,r)}finally{i!==void 0&&await p.forciblyRemoveDirectory(i),process.off(`SIGINT`,o),process.off(`SIGTERM`,o)}}async function E(e,i,a){n.makeAccessibleToSandboxUser(i);let c=await m.readProblemMarkdownFrontMatter(e),f=await u.findEntryPointFile(i,a.language);if(!f){t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:s.DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${a.language?`: language: ${a.language}`:``}`});return}let p=d.findLanguageDefinitionByPath(f);if(!p){t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:s.DecisionCode.WRONG_ANSWER,stderr:`unsupported language`});return}let g={...process.env,CI:``,FORCE_COLOR:`0`},v;if(p.prebuild)try{await p.prebuild(i),v=await u.findEntryPointFile(i,a.language)}catch(e){console.error(`prebuild error`,e),t.printTestCaseResult({testCaseId:`prebuild`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let x=v??f;if(p.buildCommand)try{let e=p.buildCommand(x),n=h.spawnSyncWithTimeout(e[0],e.slice(1),{cwd:i,encoding:`utf8`,env:g},10),r=s.DecisionCode.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.DecisionCode.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>y||n.stderr.length>y)&&(r=s.DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.DecisionCode.BUILD_ERROR,r!==s.DecisionCode.ACCEPTED){t.printTestCaseResult({testCaseId:`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,y)||void 0,stderr:n.stderr.slice(0,y)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(e){console.error(`build error`,e),t.printTestCaseResult({testCaseId:`build`,decisionCode:s.DecisionCode.BUILD_ERROR,stderr:e instanceof Error?e.message:String(e)});return}let S=await o.readTestCases(_.default.join(e,`test_cases`));S.shared?.fileInputPath&&await l.copyTestCaseFileInput(S.shared.fileInputPath,i);let C=S.find(e=>b.test(e.id)&&e.fileInputPath)?.fileInputPath;C?await l.copyTestCaseFileInput(C,i):S.some(e=>e.fileInputPath)&&console.error(`debug: no example test case has input files, so the program runs without them`);let w=Math.max(10,(c.timeLimitMs??0)/1e3),T=p.command(x),E=h.spawnSyncWithTimeout(T[0],T.slice(1),{cwd:i,encoding:`utf8`,input:a.stdin,env:g},w),D=await r.readOutputFiles(i,c.requiredOutputFilePaths??[]),O=s.DecisionCode.ACCEPTED;E.status===0?E.timeSeconds>w?O=s.DecisionCode.TIME_LIMIT_EXCEEDED:E.memoryBytes>(c.memoryLimitByte??1/0)?O=s.DecisionCode.MEMORY_LIMIT_EXCEEDED:E.stdout.length>y||E.stderr.length>y?O=s.DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED:D.length<(c.requiredOutputFilePaths?.length??0)&&(O=s.DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR):O=s.DecisionCode.RUNTIME_ERROR,t.printTestCaseResult({testCaseId:`debug`,decisionCode:O,exitStatus:E.status??void 0,stdin:a.stdin,stdout:E.stdout.slice(0,y)||void 0,stderr:E.stderr.slice(0,y)||void 0,timeSeconds:E.timeSeconds,memoryBytes:E.memoryBytes,outputFiles:D.length>0?D:void 0})}exports.stdioDebugPreset=T,exports.stdioJudgePreset=C;
2
2
  //# sourceMappingURL=stdio.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.cjs","names":["z","parseArgs","readProblemMarkdownFrontMatter","readTestCases","path","judgeByStaticAnalysis","judgesWithoutTestCases","findEntryPointFile","DecisionCode","findLanguageDefinitionByPath","spawnSyncWithTimeout","snapshotWorkingDirectory","copyTestCaseFileInput","readOutputFiles","judgeAgainstExpectations","cleanWorkingDirectory","fs","copyProblemDirToTemporaryRoot","forciblyRemoveDirectory"],"sources":["../../src/presets/stdio.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { judgeAgainstExpectations } from '../helpers/compareExpectedOutputFiles.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { makeAccessibleToSandboxUser, makeTraversableBySandboxUser } from '../helpers/sandboxUser.js';\nimport { judgesWithoutTestCases, readProblemMarkdownFrontMatter } from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport {\n copyProblemDirToTemporaryRoot,\n forciblyRemoveDirectory,\n forciblyRemoveDirectorySync,\n} from '../helpers/temporaryProblemDirCopy.js';\nimport { DecisionCode } from '../types/decisionCode.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 2;\nconst DEBUG_DEFAULT_TIMEOUT_SECONDS = 10;\n\nconst MAX_STDOUT_LENGTH = 50_000;\n// The judge server shows a test case on the problem page when its id contains `example`.\nconst EXAMPLE_TEST_CASE_ID_PATTERN = /example/;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\nconst debugParamsSchema = judgeParamsSchema.extend({\n stdin: z.string().optional(),\n});\n\ntype DebugParams = z.infer<typeof debugParamsSchema>;\n\n/**\n * A preset judge function using stdin and stdout as test cases.\n *\n * A standard stdio problem must NOT commit a `judge.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `judge.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `judge.ts`:\n * ```bash\n * bun x exercode-problem judge model_answers/java\n * ```\n *\n * Run with the optional parameters:\n * ```bash\n * bun x exercode-problem judge model_answers/java '{ \"language\": \"javascript\" }'\n * ```\n */\nexport async function stdioJudgePreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(args.cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n const staticAnalysisTestCaseResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisTestCaseResult) {\n printTestCaseResult({ testCaseId: testCases[0]?.id ?? 'prebuild', ...staticAnalysisTestCaseResult });\n return;\n }\n\n // Without an expectation, a case would accept any run; only custom harnesses may judge input-only\n // cases. A problem judged by static analysis, manual scoring or the presence of required output\n // files has an expectation of its own.\n if (\n !judgesWithoutTestCases(problemMarkdownFrontMatter) &&\n !problemMarkdownFrontMatter.requiredOutputFilePaths?.length\n ) {\n for (const testCase of testCases) {\n if (testCase.output === undefined && !(await hasExpectedFiles(testCase.fileOutputPath))) {\n throw new Error(\n `test case ${testCase.id} needs an expected output (${testCase.id}.out or a non-empty ${testCase.id}.fout/)`\n );\n }\n }\n }\n\n const originalMainFilePath = await findEntryPointFile(args.cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n prebuiltMainFilePath = await findEntryPointFile(args.cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: args.cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n\n if (testCases.length === 0) {\n printTestCaseResult({ testCaseId: 'default', decisionCode: DecisionCode.ACCEPTED });\n }\n\n for (const testCase of testCases) {\n // prepare test case\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n // run\n const timeoutSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : JUDGE_DEFAULT_TIMEOUT_SECONDS;\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd: args.cwd, encoding: 'utf8', input: testCase.input, env },\n timeoutSeconds\n );\n\n let outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n // calculate decision\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n let judgementError: string | undefined;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n } else {\n try {\n const judgement = await judgeAgainstExpectations({\n stdout: spawnResult.stdout,\n expectedStdout: testCase.output,\n fileOutputPath: testCase.fileOutputPath,\n cwd: args.cwd,\n outputFiles,\n });\n if (!judgement.matches) decisionCode = DecisionCode.WRONG_ANSWER;\n outputFiles = judgement.outputFiles;\n } catch (error) {\n // An authoring error (e.g. an oversized expected file) is reported per case, like the command preset does.\n decisionCode = DecisionCode.RUNTIME_ERROR;\n judgementError = error instanceof Error ? error.message : String(error);\n }\n }\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: testCase.input,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: (judgementError ?? spawnResult.stderr).slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n\n // clean up\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n}\n\nasync function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boolean> {\n if (fileOutputPath === undefined) return false;\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n return dirents.some((dirent) => dirent.isFile());\n}\n\n/**\n * A preset debug function using stdin and stdout as test cases. The answer directory is copied to a\n * temporary directory where it is built and run together with `_shared.fin/` and the first example\n * case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.\n *\n * A standard stdio problem must NOT commit a `debug.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `debug.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `debug.ts`:\n * ```bash\n * bun x exercode-problem debug model_answers/java '{ \"stdin\": \"1 2\" }'\n * ```\n */\nexport async function stdioDebugPreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = debugParamsSchema.parse(args.params);\n\n // Everything (build, input files, run) happens in a disposable copy of the answer directory, so\n // the developer's files are never touched and whatever the submission leaves behind goes with it.\n // The copy keeps the directory hierarchy and links every ancestor `node_modules`, so packages the\n // answer resolves from its parents still resolve.\n // A terminated debug run must not leave the copy behind; `finally` does not run on a signal, so\n // the handlers learn the root as soon as it is created and stay until it is removed.\n let tempRoot: string | undefined;\n const removeOnSignal = (): void => {\n if (tempRoot !== undefined) forciblyRemoveDirectorySync(tempRoot);\n process.exit(1);\n };\n process.once('SIGINT', removeOnSignal);\n process.once('SIGTERM', removeOnSignal);\n try {\n const copy = await copyProblemDirToTemporaryRoot(args.cwd, { onTempRootCreated: (root) => (tempRoot = root) });\n // `mkdtemp` creates a 0700 root: the sandbox user only traverses the root and the synthesized\n // ancestors, and gets full access to the copied answer directory alone.\n makeTraversableBySandboxUser(copy.tempRoot, path.dirname(copy.copiedProblemDir));\n await debugInTemporaryCopy(problemDir, copy.copiedProblemDir, params);\n } finally {\n if (tempRoot !== undefined) await forciblyRemoveDirectory(tempRoot);\n process.off('SIGINT', removeOnSignal);\n process.off('SIGTERM', removeOnSignal);\n }\n}\n\nasync function debugInTemporaryCopy(problemDir: string, cwd: string, params: DebugParams): Promise<void> {\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n\n const originalMainFilePath = await findEntryPointFile(cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(cwd);\n prebuiltMainFilePath = await findEntryPointFile(cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n // A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the\n // first example case (the cases a learner may see), placed the way the judge does. Hidden cases'\n // input files are never handed to learner code.\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);\n const exampleFileInputPath = testCases.find(\n (testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath\n )?.fileInputPath;\n if (exampleFileInputPath) {\n await copyTestCaseFileInput(exampleFileInputPath, cwd);\n } else if (testCases.some((testCase) => testCase.fileInputPath)) {\n console.error('debug: no example test case has input files, so the program runs without them');\n }\n\n const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd, encoding: 'utf8', input: params.stdin, env },\n timeoutSeconds\n );\n\n const outputFiles = await readOutputFiles(cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n }\n\n printTestCaseResult({\n testCaseId: 'debug',\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: params.stdin,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: spawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n}\n"],"mappings":"g8BAyBA,MAIM,EAAoB,IAEpB,EAA+B,UAE/B,EAAoBA,EAAAA,EAAE,OAAO,CACjC,SAAUA,EAAAA,EAAE,MAAM,CAACA,EAAAA,EAAE,OAAO,EAAGA,EAAAA,EAAE,MAAMA,EAAAA,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC,EAEK,EAAoB,EAAkB,OAAO,CACjD,MAAOA,EAAAA,EAAE,OAAO,CAAC,CAAC,SAAS,CAC7B,CAAC,EAsBD,eAAsB,EAAiB,EAAmC,CACxE,IAAM,EAAOC,EAAAA,UAAU,QAAQ,IAAI,EACnC,GAAI,CAAC,EAAK,IAAK,MAAU,MAAM,uBAAuB,EACtD,IAAM,EAAS,EAAkB,MAAM,EAAK,MAAM,EAGlD,EAAA,4BAA4B,EAAK,GAAG,EAEpC,IAAM,EAA6B,MAAMC,EAAAA,+BAA+B,CAAU,EAC5E,EAAY,MAAMC,EAAAA,cAAcC,EAAAA,QAAK,KAAK,EAAY,YAAY,CAAC,EACnE,EAA+B,MAAMC,E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F,EAAeA,EAAAA,aAAa,2BACnB,EAAY,QAAU,EAA2B,yBAAyB,QAAU,KAC7F,EAAeA,EAAAA,aAAa,oCAR5B,EAAeA,EAAAA,aAAa,cAW9B,EAAA,oBAAoB,CAClB,WAAY,QACZ,eACA,WAAY,EAAY,QAAU,IAAA,GAClC,MAAO,EAAO,MACd,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,YAAa,EAAY,YACzB,YAAa,EAAY,YACzB,YAAa,EAAY,OAAS,EAAI,EAAc,IAAA,EACtD,CAAC,CACH"}
1
+ {"version":3,"file":"stdio.cjs","names":["z","parseArgs","readProblemMarkdownFrontMatter","readTestCases","path","judgesTestCasesWithoutExpectations","judgeByStaticAnalysis","findEntryPointFile","DecisionCode","findLanguageDefinitionByPath","spawnSyncWithTimeout","snapshotWorkingDirectory","copyTestCaseFileInput","readOutputFiles","judgeAgainstExpectations","cleanWorkingDirectory","fs","copyProblemDirToTemporaryRoot","forciblyRemoveDirectory"],"sources":["../../src/presets/stdio.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { judgeAgainstExpectations } from '../helpers/compareExpectedOutputFiles.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { makeAccessibleToSandboxUser, makeTraversableBySandboxUser } from '../helpers/sandboxUser.js';\nimport {\n judgesTestCasesWithoutExpectations,\n readProblemMarkdownFrontMatter,\n} from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport {\n copyProblemDirToTemporaryRoot,\n forciblyRemoveDirectory,\n forciblyRemoveDirectorySync,\n} from '../helpers/temporaryProblemDirCopy.js';\nimport { DecisionCode } from '../types/decisionCode.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 2;\nconst DEBUG_DEFAULT_TIMEOUT_SECONDS = 10;\n\nconst MAX_STDOUT_LENGTH = 50_000;\n// The judge server shows a test case on the problem page when its id contains `example`.\nconst EXAMPLE_TEST_CASE_ID_PATTERN = /example/;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\nconst debugParamsSchema = judgeParamsSchema.extend({\n stdin: z.string().optional(),\n});\n\ntype DebugParams = z.infer<typeof debugParamsSchema>;\n\n/**\n * A preset judge function using stdin and stdout as test cases.\n *\n * A standard stdio problem must NOT commit a `judge.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `judge.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `judge.ts`:\n * ```bash\n * bun x exercode-problem judge model_answers/java\n * ```\n *\n * Run with the optional parameters:\n * ```bash\n * bun x exercode-problem judge model_answers/java '{ \"language\": \"javascript\" }'\n * ```\n */\nexport async function stdioJudgePreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(args.cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n // Without an expectation, a case would accept any run; only custom harnesses may judge input-only\n // cases. A problem judged by manual scoring or the presence of required output files has an\n // expectation of its own. Checked before the static analysis so that an authoring error surfaces\n // regardless of the submission.\n if (!judgesTestCasesWithoutExpectations(problemMarkdownFrontMatter)) {\n for (const testCase of testCases) {\n if (testCase.output === undefined && !(await hasExpectedFiles(testCase.fileOutputPath))) {\n throw new Error(\n `test case ${testCase.id} needs an expected output (${testCase.id}.out or a non-empty ${testCase.id}.fout/)`\n );\n }\n }\n }\n\n const staticAnalysisTestCaseResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisTestCaseResult) {\n printTestCaseResult({ testCaseId: testCases[0]?.id ?? 'prebuild', ...staticAnalysisTestCaseResult });\n return;\n }\n\n const originalMainFilePath = await findEntryPointFile(args.cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n prebuiltMainFilePath = await findEntryPointFile(args.cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: args.cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n\n if (testCases.length === 0) {\n printTestCaseResult({ testCaseId: 'default', decisionCode: DecisionCode.ACCEPTED });\n }\n\n for (const testCase of testCases) {\n // prepare test case\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n // run\n const timeoutSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : JUDGE_DEFAULT_TIMEOUT_SECONDS;\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd: args.cwd, encoding: 'utf8', input: testCase.input, env },\n timeoutSeconds\n );\n\n let outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n // calculate decision\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n let judgementError: string | undefined;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n } else {\n try {\n const judgement = await judgeAgainstExpectations({\n stdout: spawnResult.stdout,\n expectedStdout: testCase.output,\n fileOutputPath: testCase.fileOutputPath,\n cwd: args.cwd,\n outputFiles,\n });\n if (!judgement.matches) decisionCode = DecisionCode.WRONG_ANSWER;\n outputFiles = judgement.outputFiles;\n } catch (error) {\n // An authoring error (e.g. an oversized expected file) is reported per case, like the command preset does.\n decisionCode = DecisionCode.RUNTIME_ERROR;\n judgementError = error instanceof Error ? error.message : String(error);\n }\n }\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: testCase.input,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: (judgementError ?? spawnResult.stderr).slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n\n // clean up\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n}\n\nasync function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boolean> {\n if (fileOutputPath === undefined) return false;\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n return dirents.some((dirent) => dirent.isFile());\n}\n\n/**\n * A preset debug function using stdin and stdout as test cases. The answer directory is copied to a\n * temporary directory where it is built and run together with `_shared.fin/` and the first example\n * case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.\n *\n * A standard stdio problem must NOT commit a `debug.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `debug.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `debug.ts`:\n * ```bash\n * bun x exercode-problem debug model_answers/java '{ \"stdin\": \"1 2\" }'\n * ```\n */\nexport async function stdioDebugPreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = debugParamsSchema.parse(args.params);\n\n // Everything (build, input files, run) happens in a disposable copy of the answer directory, so\n // the developer's files are never touched and whatever the submission leaves behind goes with it.\n // The copy keeps the directory hierarchy and links every ancestor `node_modules`, so packages the\n // answer resolves from its parents still resolve.\n // A terminated debug run must not leave the copy behind; `finally` does not run on a signal, so\n // the handlers learn the root as soon as it is created and stay until it is removed.\n let tempRoot: string | undefined;\n const removeOnSignal = (): void => {\n if (tempRoot !== undefined) forciblyRemoveDirectorySync(tempRoot);\n process.exit(1);\n };\n process.once('SIGINT', removeOnSignal);\n process.once('SIGTERM', removeOnSignal);\n try {\n const copy = await copyProblemDirToTemporaryRoot(args.cwd, { onTempRootCreated: (root) => (tempRoot = root) });\n // `mkdtemp` creates a 0700 root: the sandbox user only traverses the root and the synthesized\n // ancestors, and gets full access to the copied answer directory alone.\n makeTraversableBySandboxUser(copy.tempRoot, path.dirname(copy.copiedProblemDir));\n await debugInTemporaryCopy(problemDir, copy.copiedProblemDir, params);\n } finally {\n if (tempRoot !== undefined) await forciblyRemoveDirectory(tempRoot);\n process.off('SIGINT', removeOnSignal);\n process.off('SIGTERM', removeOnSignal);\n }\n}\n\nasync function debugInTemporaryCopy(problemDir: string, cwd: string, params: DebugParams): Promise<void> {\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n\n const originalMainFilePath = await findEntryPointFile(cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(cwd);\n prebuiltMainFilePath = await findEntryPointFile(cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n // A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the\n // first example case (the cases a learner may see), placed the way the judge does. Hidden cases'\n // input files are never handed to learner code.\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);\n const exampleFileInputPath = testCases.find(\n (testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath\n )?.fileInputPath;\n if (exampleFileInputPath) {\n await copyTestCaseFileInput(exampleFileInputPath, cwd);\n } else if (testCases.some((testCase) => testCase.fileInputPath)) {\n console.error('debug: no example test case has input files, so the program runs without them');\n }\n\n const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd, encoding: 'utf8', input: params.stdin, env },\n timeoutSeconds\n );\n\n const outputFiles = await readOutputFiles(cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n }\n\n printTestCaseResult({\n testCaseId: 'debug',\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: params.stdin,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: spawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n}\n"],"mapp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GAAK,EAAS,aAC3E,CAAC,EAAE,cACC,EACF,MAAMA,EAAAA,sBAAsB,EAAsB,CAAG,EAC5C,EAAU,KAAM,GAAa,EAAS,aAAa,GAC5D,QAAQ,MAAM,+EAA+E,EAG/F,IAAM,EAAiB,KAAK,IAAI,IAAgC,EAA2B,aAAe,GAAK,GAAI,EAE7G,EAAU,EAAmB,QAAQ,CAAY,EAEjD,EAAcF,EAAAA,qBAClB,EAAQ,GACR,EAAQ,MAAM,CAAC,EACf,CAAE,MAAK,SAAU,OAAQ,MAAO,EAAO,MAAO,KAAI,EAClD,CACF,EAEM,EAAc,MAAMG,EAAAA,gBAAgB,EAAK,EAA2B,yBAA2B,CAAC,CAAC,EAEnG,EAA6BL,EAAAA,aAAa,SAE1C,EAAY,SAAW,EAEhB,EAAY,YAAc,EACnC,EAAeA,EAAAA,aAAa,oBACnB,EAAY,aAAe,EAA2B,iBAAmB,KAClF,EAAeA,EAAAA,aAAa,sBACnB,EAAY,OAAO,OAAS,GAAqB,EAAY,OAAO,OAAS,EACtF,EAAeA,EAAAA,aAAa,2BACnB,EAAY,QAAU,EAA2B,yBAAyB,QAAU,KAC7F,EAAeA,EAAAA,aAAa,oCAR5B,EAAeA,EAAAA,aAAa,cAW9B,EAAA,oBAAoB,CAClB,WAAY,QACZ,eACA,WAAY,EAAY,QAAU,IAAA,GAClC,MAAO,EAAO,MACd,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,YAAa,EAAY,YACzB,YAAa,EAAY,YACzB,YAAa,EAAY,OAAS,EAAI,EAAc,IAAA,EACtD,CAAC,CACH"}
@@ -1,2 +1,2 @@
1
- import{printTestCaseResult as e}from"../helpers/printTestCaseResult.js";import{makeAccessibleToSandboxUser as t,makeTraversableBySandboxUser as n}from"../helpers/sandboxUser.js";import{readOutputFiles as r}from"../helpers/readOutputFiles.js";import{judgeAgainstExpectations as i}from"../helpers/compareExpectedOutputFiles.js";import{parseArgs as a}from"../helpers/parseArgs.js";import{readTestCases as o}from"../helpers/readTestCases.js";import{DecisionCode as s}from"../types/decisionCode.js";import{cleanWorkingDirectory as c,snapshotWorkingDirectory as l}from"../helpers/cleanWorkingDirectory.js";import{copyTestCaseFileInput as u}from"../helpers/copyTestCaseFileInput.js";import{findEntryPointFile as d}from"../helpers/findEntryPointFile.js";import{findLanguageDefinitionByPath as f}from"../helpers/findLanguageDefinitionByPath.js";import{judgeByStaticAnalysis as p}from"../helpers/judgeByStaticAnalysis.js";import{copyProblemDirToTemporaryRoot as m,forciblyRemoveDirectory as h,forciblyRemoveDirectorySync as g}from"../helpers/temporaryProblemDirCopy.js";import{judgesWithoutTestCases as _,readProblemMarkdownFrontMatter as v}from"../helpers/readProblemMarkdownFrontMatter.js";import{spawnSyncWithTimeout as y}from"../helpers/spawnSyncWithTimeout.js";import b from"node:fs";import x from"node:path";import{z as S}from"zod";const C=5e4,w=/example/,T=S.object({language:S.union([S.string(),S.array(S.string())]).optional()}),E=T.extend({stdin:S.string().optional()});async function D(n){let m=a(process.argv);if(!m.cwd)throw Error(`cwd argument required`);let h=T.parse(m.params);t(m.cwd);let g=await v(n),b=await o(x.join(n,`test_cases`)),S=await p(m.cwd,g);if(S){e({testCaseId:b[0]?.id??`prebuild`,...S});return}if(!_(g)&&!g.requiredOutputFilePaths?.length){for(let e of b)if(e.output===void 0&&!await O(e.fileOutputPath))throw Error(`test case ${e.id} needs an expected output (${e.id}.out or a non-empty ${e.id}.fout/)`)}let w=await d(m.cwd,h.language);if(!w){e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${h.language?`: language: ${h.language}`:``}`});return}let E=f(w);if(!E){e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.WRONG_ANSWER,stderr:`unsupported language`});return}let D={...process.env,CI:``,FORCE_COLOR:`0`},k;if(E.prebuild)try{await E.prebuild(m.cwd),k=await d(m.cwd,h.language)}catch(t){console.error(`prebuild error`,t),e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let A=k??w;if(E.buildCommand)try{let t=E.buildCommand(A),n=y(t[0],t.slice(1),{cwd:m.cwd,encoding:`utf8`,env:D},10),r=s.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>C||n.stderr.length>C)&&(r=s.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.BUILD_ERROR,r!==s.ACCEPTED){e({testCaseId:b[0]?.id??`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,C)||void 0,stderr:n.stderr.slice(0,C)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(t){console.error(`build error`,t),e({testCaseId:b[0]?.id??`build`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let j=await l(m.cwd);b.length===0&&e({testCaseId:`default`,decisionCode:s.ACCEPTED});for(let t of b){b.shared?.fileInputPath&&await u(b.shared.fileInputPath,m.cwd),t.fileInputPath&&await u(t.fileInputPath,m.cwd);let n=typeof g.timeLimitMs==`number`?g.timeLimitMs/1e3:2,a=E.command(A),o=y(a[0],a.slice(1),{cwd:m.cwd,encoding:`utf8`,input:t.input,env:D},n),l=await r(m.cwd,g.requiredOutputFilePaths??[]),d=s.ACCEPTED,f;if(o.status!==0)d=s.RUNTIME_ERROR;else if(o.timeSeconds>n)d=s.TIME_LIMIT_EXCEEDED;else if(o.memoryBytes>(g.memoryLimitByte??1/0))d=s.MEMORY_LIMIT_EXCEEDED;else if(o.stdout.length>C||o.stderr.length>C)d=s.OUTPUT_SIZE_LIMIT_EXCEEDED;else if(l.length<(g.requiredOutputFilePaths?.length??0))d=s.MISSING_REQUIRED_OUTPUT_FILE_ERROR;else try{let e=await i({stdout:o.stdout,expectedStdout:t.output,fileOutputPath:t.fileOutputPath,cwd:m.cwd,outputFiles:l});e.matches||(d=s.WRONG_ANSWER),l=e.outputFiles}catch(e){d=s.RUNTIME_ERROR,f=e instanceof Error?e.message:String(e)}if(e({testCaseId:t.id,decisionCode:d,exitStatus:o.status??void 0,stdin:t.input,stdout:o.stdout.slice(0,C)||void 0,stderr:(f??o.stderr).slice(0,C)||void 0,timeSeconds:o.timeSeconds,memoryBytes:o.memoryBytes,outputFiles:l.length>0?l:void 0}),await c(m.cwd,j),d!==s.ACCEPTED)break}}async function O(e){return e!==void 0&&(await b.promises.readdir(e,{withFileTypes:!0,recursive:!0})).some(e=>e.isFile())}async function k(e){let t=a(process.argv);if(!t.cwd)throw Error(`cwd argument required`);let r=E.parse(t.params),i,o=()=>{i!==void 0&&g(i),process.exit(1)};process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{let a=await m(t.cwd,{onTempRootCreated:e=>i=e});n(a.tempRoot,x.dirname(a.copiedProblemDir)),await A(e,a.copiedProblemDir,r)}finally{i!==void 0&&await h(i),process.off(`SIGINT`,o),process.off(`SIGTERM`,o)}}async function A(n,i,a){t(i);let c=await v(n),l=await d(i,a.language);if(!l){e({testCaseId:`prebuild`,decisionCode:s.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${a.language?`: language: ${a.language}`:``}`});return}let p=f(l);if(!p){e({testCaseId:`prebuild`,decisionCode:s.WRONG_ANSWER,stderr:`unsupported language`});return}let m={...process.env,CI:``,FORCE_COLOR:`0`},h;if(p.prebuild)try{await p.prebuild(i),h=await d(i,a.language)}catch(t){console.error(`prebuild error`,t),e({testCaseId:`prebuild`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let g=h??l;if(p.buildCommand)try{let t=p.buildCommand(g),n=y(t[0],t.slice(1),{cwd:i,encoding:`utf8`,env:m},10),r=s.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>C||n.stderr.length>C)&&(r=s.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.BUILD_ERROR,r!==s.ACCEPTED){e({testCaseId:`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,C)||void 0,stderr:n.stderr.slice(0,C)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(t){console.error(`build error`,t),e({testCaseId:`build`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let _=await o(x.join(n,`test_cases`));_.shared?.fileInputPath&&await u(_.shared.fileInputPath,i);let b=_.find(e=>w.test(e.id)&&e.fileInputPath)?.fileInputPath;b?await u(b,i):_.some(e=>e.fileInputPath)&&console.error(`debug: no example test case has input files, so the program runs without them`);let S=Math.max(10,(c.timeLimitMs??0)/1e3),T=p.command(g),E=y(T[0],T.slice(1),{cwd:i,encoding:`utf8`,input:a.stdin,env:m},S),D=await r(i,c.requiredOutputFilePaths??[]),O=s.ACCEPTED;E.status===0?E.timeSeconds>S?O=s.TIME_LIMIT_EXCEEDED:E.memoryBytes>(c.memoryLimitByte??1/0)?O=s.MEMORY_LIMIT_EXCEEDED:E.stdout.length>C||E.stderr.length>C?O=s.OUTPUT_SIZE_LIMIT_EXCEEDED:D.length<(c.requiredOutputFilePaths?.length??0)&&(O=s.MISSING_REQUIRED_OUTPUT_FILE_ERROR):O=s.RUNTIME_ERROR,e({testCaseId:`debug`,decisionCode:O,exitStatus:E.status??void 0,stdin:a.stdin,stdout:E.stdout.slice(0,C)||void 0,stderr:E.stderr.slice(0,C)||void 0,timeSeconds:E.timeSeconds,memoryBytes:E.memoryBytes,outputFiles:D.length>0?D:void 0})}export{k as stdioDebugPreset,D as stdioJudgePreset};
1
+ import{printTestCaseResult as e}from"../helpers/printTestCaseResult.js";import{makeAccessibleToSandboxUser as t,makeTraversableBySandboxUser as n}from"../helpers/sandboxUser.js";import{readOutputFiles as r}from"../helpers/readOutputFiles.js";import{judgeAgainstExpectations as i}from"../helpers/compareExpectedOutputFiles.js";import{parseArgs as a}from"../helpers/parseArgs.js";import{readTestCases as o}from"../helpers/readTestCases.js";import{DecisionCode as s}from"../types/decisionCode.js";import{cleanWorkingDirectory as c,snapshotWorkingDirectory as l}from"../helpers/cleanWorkingDirectory.js";import{copyTestCaseFileInput as u}from"../helpers/copyTestCaseFileInput.js";import{findEntryPointFile as d}from"../helpers/findEntryPointFile.js";import{findLanguageDefinitionByPath as f}from"../helpers/findLanguageDefinitionByPath.js";import{judgeByStaticAnalysis as p}from"../helpers/judgeByStaticAnalysis.js";import{copyProblemDirToTemporaryRoot as m,forciblyRemoveDirectory as h,forciblyRemoveDirectorySync as g}from"../helpers/temporaryProblemDirCopy.js";import{judgesTestCasesWithoutExpectations as _,readProblemMarkdownFrontMatter as v}from"../helpers/readProblemMarkdownFrontMatter.js";import{spawnSyncWithTimeout as y}from"../helpers/spawnSyncWithTimeout.js";import b from"node:fs";import x from"node:path";import{z as S}from"zod";const C=5e4,w=/example/,T=S.object({language:S.union([S.string(),S.array(S.string())]).optional()}),E=T.extend({stdin:S.string().optional()});async function D(n){let m=a(process.argv);if(!m.cwd)throw Error(`cwd argument required`);let h=T.parse(m.params);t(m.cwd);let g=await v(n),b=await o(x.join(n,`test_cases`));if(!_(g)){for(let e of b)if(e.output===void 0&&!await O(e.fileOutputPath))throw Error(`test case ${e.id} needs an expected output (${e.id}.out or a non-empty ${e.id}.fout/)`)}let S=await p(m.cwd,g);if(S){e({testCaseId:b[0]?.id??`prebuild`,...S});return}let w=await d(m.cwd,h.language);if(!w){e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${h.language?`: language: ${h.language}`:``}`});return}let E=f(w);if(!E){e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.WRONG_ANSWER,stderr:`unsupported language`});return}let D={...process.env,CI:``,FORCE_COLOR:`0`},k;if(E.prebuild)try{await E.prebuild(m.cwd),k=await d(m.cwd,h.language)}catch(t){console.error(`prebuild error`,t),e({testCaseId:b[0]?.id??`prebuild`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let A=k??w;if(E.buildCommand)try{let t=E.buildCommand(A),n=y(t[0],t.slice(1),{cwd:m.cwd,encoding:`utf8`,env:D},10),r=s.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>C||n.stderr.length>C)&&(r=s.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.BUILD_ERROR,r!==s.ACCEPTED){e({testCaseId:b[0]?.id??`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,C)||void 0,stderr:n.stderr.slice(0,C)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(t){console.error(`build error`,t),e({testCaseId:b[0]?.id??`build`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let j=await l(m.cwd);b.length===0&&e({testCaseId:`default`,decisionCode:s.ACCEPTED});for(let t of b){b.shared?.fileInputPath&&await u(b.shared.fileInputPath,m.cwd),t.fileInputPath&&await u(t.fileInputPath,m.cwd);let n=typeof g.timeLimitMs==`number`?g.timeLimitMs/1e3:2,a=E.command(A),o=y(a[0],a.slice(1),{cwd:m.cwd,encoding:`utf8`,input:t.input,env:D},n),l=await r(m.cwd,g.requiredOutputFilePaths??[]),d=s.ACCEPTED,f;if(o.status!==0)d=s.RUNTIME_ERROR;else if(o.timeSeconds>n)d=s.TIME_LIMIT_EXCEEDED;else if(o.memoryBytes>(g.memoryLimitByte??1/0))d=s.MEMORY_LIMIT_EXCEEDED;else if(o.stdout.length>C||o.stderr.length>C)d=s.OUTPUT_SIZE_LIMIT_EXCEEDED;else if(l.length<(g.requiredOutputFilePaths?.length??0))d=s.MISSING_REQUIRED_OUTPUT_FILE_ERROR;else try{let e=await i({stdout:o.stdout,expectedStdout:t.output,fileOutputPath:t.fileOutputPath,cwd:m.cwd,outputFiles:l});e.matches||(d=s.WRONG_ANSWER),l=e.outputFiles}catch(e){d=s.RUNTIME_ERROR,f=e instanceof Error?e.message:String(e)}if(e({testCaseId:t.id,decisionCode:d,exitStatus:o.status??void 0,stdin:t.input,stdout:o.stdout.slice(0,C)||void 0,stderr:(f??o.stderr).slice(0,C)||void 0,timeSeconds:o.timeSeconds,memoryBytes:o.memoryBytes,outputFiles:l.length>0?l:void 0}),await c(m.cwd,j),d!==s.ACCEPTED)break}}async function O(e){return e!==void 0&&(await b.promises.readdir(e,{withFileTypes:!0,recursive:!0})).some(e=>e.isFile())}async function k(e){let t=a(process.argv);if(!t.cwd)throw Error(`cwd argument required`);let r=E.parse(t.params),i,o=()=>{i!==void 0&&g(i),process.exit(1)};process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{let a=await m(t.cwd,{onTempRootCreated:e=>i=e});n(a.tempRoot,x.dirname(a.copiedProblemDir)),await A(e,a.copiedProblemDir,r)}finally{i!==void 0&&await h(i),process.off(`SIGINT`,o),process.off(`SIGTERM`,o)}}async function A(n,i,a){t(i);let c=await v(n),l=await d(i,a.language);if(!l){e({testCaseId:`prebuild`,decisionCode:s.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,stderr:`main file not found${a.language?`: language: ${a.language}`:``}`});return}let p=f(l);if(!p){e({testCaseId:`prebuild`,decisionCode:s.WRONG_ANSWER,stderr:`unsupported language`});return}let m={...process.env,CI:``,FORCE_COLOR:`0`},h;if(p.prebuild)try{await p.prebuild(i),h=await d(i,a.language)}catch(t){console.error(`prebuild error`,t),e({testCaseId:`prebuild`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let g=h??l;if(p.buildCommand)try{let t=p.buildCommand(g),n=y(t[0],t.slice(1),{cwd:i,encoding:`utf8`,env:m},10),r=s.ACCEPTED;if(n.status===0?n.timeSeconds>10?r=s.BUILD_TIME_LIMIT_EXCEEDED:(n.stdout.length>C||n.stderr.length>C)&&(r=s.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED):r=s.BUILD_ERROR,r!==s.ACCEPTED){e({testCaseId:`build`,decisionCode:r,exitStatus:n.status??void 0,stdout:n.stdout.slice(0,C)||void 0,stderr:n.stderr.slice(0,C)||void 0,timeSeconds:n.timeSeconds,memoryBytes:n.memoryBytes});return}}catch(t){console.error(`build error`,t),e({testCaseId:`build`,decisionCode:s.BUILD_ERROR,stderr:t instanceof Error?t.message:String(t)});return}let _=await o(x.join(n,`test_cases`));_.shared?.fileInputPath&&await u(_.shared.fileInputPath,i);let b=_.find(e=>w.test(e.id)&&e.fileInputPath)?.fileInputPath;b?await u(b,i):_.some(e=>e.fileInputPath)&&console.error(`debug: no example test case has input files, so the program runs without them`);let S=Math.max(10,(c.timeLimitMs??0)/1e3),T=p.command(g),E=y(T[0],T.slice(1),{cwd:i,encoding:`utf8`,input:a.stdin,env:m},S),D=await r(i,c.requiredOutputFilePaths??[]),O=s.ACCEPTED;E.status===0?E.timeSeconds>S?O=s.TIME_LIMIT_EXCEEDED:E.memoryBytes>(c.memoryLimitByte??1/0)?O=s.MEMORY_LIMIT_EXCEEDED:E.stdout.length>C||E.stderr.length>C?O=s.OUTPUT_SIZE_LIMIT_EXCEEDED:D.length<(c.requiredOutputFilePaths?.length??0)&&(O=s.MISSING_REQUIRED_OUTPUT_FILE_ERROR):O=s.RUNTIME_ERROR,e({testCaseId:`debug`,decisionCode:O,exitStatus:E.status??void 0,stdin:a.stdin,stdout:E.stdout.slice(0,C)||void 0,stderr:E.stderr.slice(0,C)||void 0,timeSeconds:E.timeSeconds,memoryBytes:E.memoryBytes,outputFiles:D.length>0?D:void 0})}export{k as stdioDebugPreset,D as stdioJudgePreset};
2
2
  //# sourceMappingURL=stdio.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"stdio.js","names":[],"sources":["../../src/presets/stdio.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { judgeAgainstExpectations } from '../helpers/compareExpectedOutputFiles.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { makeAccessibleToSandboxUser, makeTraversableBySandboxUser } from '../helpers/sandboxUser.js';\nimport { judgesWithoutTestCases, readProblemMarkdownFrontMatter } from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport {\n copyProblemDirToTemporaryRoot,\n forciblyRemoveDirectory,\n forciblyRemoveDirectorySync,\n} from '../helpers/temporaryProblemDirCopy.js';\nimport { DecisionCode } from '../types/decisionCode.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 2;\nconst DEBUG_DEFAULT_TIMEOUT_SECONDS = 10;\n\nconst MAX_STDOUT_LENGTH = 50_000;\n// The judge server shows a test case on the problem page when its id contains `example`.\nconst EXAMPLE_TEST_CASE_ID_PATTERN = /example/;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\nconst debugParamsSchema = judgeParamsSchema.extend({\n stdin: z.string().optional(),\n});\n\ntype DebugParams = z.infer<typeof debugParamsSchema>;\n\n/**\n * A preset judge function using stdin and stdout as test cases.\n *\n * A standard stdio problem must NOT commit a `judge.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `judge.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `judge.ts`:\n * ```bash\n * bun x exercode-problem judge model_answers/java\n * ```\n *\n * Run with the optional parameters:\n * ```bash\n * bun x exercode-problem judge model_answers/java '{ \"language\": \"javascript\" }'\n * ```\n */\nexport async function stdioJudgePreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(args.cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n const staticAnalysisTestCaseResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisTestCaseResult) {\n printTestCaseResult({ testCaseId: testCases[0]?.id ?? 'prebuild', ...staticAnalysisTestCaseResult });\n return;\n }\n\n // Without an expectation, a case would accept any run; only custom harnesses may judge input-only\n // cases. A problem judged by static analysis, manual scoring or the presence of required output\n // files has an expectation of its own.\n if (\n !judgesWithoutTestCases(problemMarkdownFrontMatter) &&\n !problemMarkdownFrontMatter.requiredOutputFilePaths?.length\n ) {\n for (const testCase of testCases) {\n if (testCase.output === undefined && !(await hasExpectedFiles(testCase.fileOutputPath))) {\n throw new Error(\n `test case ${testCase.id} needs an expected output (${testCase.id}.out or a non-empty ${testCase.id}.fout/)`\n );\n }\n }\n }\n\n const originalMainFilePath = await findEntryPointFile(args.cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n prebuiltMainFilePath = await findEntryPointFile(args.cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: args.cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n\n if (testCases.length === 0) {\n printTestCaseResult({ testCaseId: 'default', decisionCode: DecisionCode.ACCEPTED });\n }\n\n for (const testCase of testCases) {\n // prepare test case\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n // run\n const timeoutSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : JUDGE_DEFAULT_TIMEOUT_SECONDS;\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd: args.cwd, encoding: 'utf8', input: testCase.input, env },\n timeoutSeconds\n );\n\n let outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n // calculate decision\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n let judgementError: string | undefined;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n } else {\n try {\n const judgement = await judgeAgainstExpectations({\n stdout: spawnResult.stdout,\n expectedStdout: testCase.output,\n fileOutputPath: testCase.fileOutputPath,\n cwd: args.cwd,\n outputFiles,\n });\n if (!judgement.matches) decisionCode = DecisionCode.WRONG_ANSWER;\n outputFiles = judgement.outputFiles;\n } catch (error) {\n // An authoring error (e.g. an oversized expected file) is reported per case, like the command preset does.\n decisionCode = DecisionCode.RUNTIME_ERROR;\n judgementError = error instanceof Error ? error.message : String(error);\n }\n }\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: testCase.input,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: (judgementError ?? spawnResult.stderr).slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n\n // clean up\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n}\n\nasync function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boolean> {\n if (fileOutputPath === undefined) return false;\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n return dirents.some((dirent) => dirent.isFile());\n}\n\n/**\n * A preset debug function using stdin and stdout as test cases. The answer directory is copied to a\n * temporary directory where it is built and run together with `_shared.fin/` and the first example\n * case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.\n *\n * A standard stdio problem must NOT commit a `debug.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `debug.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `debug.ts`:\n * ```bash\n * bun x exercode-problem debug model_answers/java '{ \"stdin\": \"1 2\" }'\n * ```\n */\nexport async function stdioDebugPreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = debugParamsSchema.parse(args.params);\n\n // Everything (build, input files, run) happens in a disposable copy of the answer directory, so\n // the developer's files are never touched and whatever the submission leaves behind goes with it.\n // The copy keeps the directory hierarchy and links every ancestor `node_modules`, so packages the\n // answer resolves from its parents still resolve.\n // A terminated debug run must not leave the copy behind; `finally` does not run on a signal, so\n // the handlers learn the root as soon as it is created and stay until it is removed.\n let tempRoot: string | undefined;\n const removeOnSignal = (): void => {\n if (tempRoot !== undefined) forciblyRemoveDirectorySync(tempRoot);\n process.exit(1);\n };\n process.once('SIGINT', removeOnSignal);\n process.once('SIGTERM', removeOnSignal);\n try {\n const copy = await copyProblemDirToTemporaryRoot(args.cwd, { onTempRootCreated: (root) => (tempRoot = root) });\n // `mkdtemp` creates a 0700 root: the sandbox user only traverses the root and the synthesized\n // ancestors, and gets full access to the copied answer directory alone.\n makeTraversableBySandboxUser(copy.tempRoot, path.dirname(copy.copiedProblemDir));\n await debugInTemporaryCopy(problemDir, copy.copiedProblemDir, params);\n } finally {\n if (tempRoot !== undefined) await forciblyRemoveDirectory(tempRoot);\n process.off('SIGINT', removeOnSignal);\n process.off('SIGTERM', removeOnSignal);\n }\n}\n\nasync function debugInTemporaryCopy(problemDir: string, cwd: string, params: DebugParams): Promise<void> {\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n\n const originalMainFilePath = await findEntryPointFile(cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(cwd);\n prebuiltMainFilePath = await findEntryPointFile(cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n // A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the\n // first example case (the cases a learner may see), placed the way the judge does. Hidden cases'\n // input files are never handed to learner code.\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);\n const exampleFileInputPath = testCases.find(\n (testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath\n )?.fileInputPath;\n if (exampleFileInputPath) {\n await copyTestCaseFileInput(exampleFileInputPath, cwd);\n } else if (testCases.some((testCase) => testCase.fileInputPath)) {\n console.error('debug: no example test case has input files, so the program runs without them');\n }\n\n const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd, encoding: 'utf8', input: params.stdin, env },\n timeoutSeconds\n );\n\n const outputFiles = await readOutputFiles(cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n }\n\n printTestCaseResult({\n testCaseId: 'debug',\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: params.stdin,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: spawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n}\n"],"mappings":"gzCAyBA,MAIM,EAAoB,IAEpB,EAA+B,UAE/B,EAAoB,EAAE,OAAO,CACjC,SAAU,EAAE,MAAM,CAAC,EAAE,OAAO,EAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC,EAEK,EAAoB,EAAkB,OAAO,CACjD,MAAO,EAAE,OAAO,CAAC,CAAC,SAAS,CAC7B,CAAC,EAsBD,eAAsB,EAAiB,EAAmC,CACxE,IAAM,EAAO,EAAU,QAAQ,IAAI,EACnC,GAAI,CAAC,EAAK,IAAK,MAAU,MAAM,uBAAuB,EACtD,IAAM,EAAS,EAAkB,MAAM,EAAK,MAAM,EAGlD,EAA4B,EAAK,GAAG,EAEpC,IAAM,EAA6B,MAAM,EAA+B,CAAU,EAC5E,EAAY,MAAM,EAAc,EAAK,KAAK,EAAY,YAAY,CAAC,EACnE,EAA+B,MAAM,EAAsB,EAAK,IAAK,CAA0B,EACrG,GAAI,EAA8B,CAChC,EAAoB,CAAE,WAAY,EAAU,EAAE,EAAE,IAAM,WAAY,GAAG,CAA6B,CAAC,EACnG,MACF,CAKA,GACE,CAAC,EAAuB,CAA0B,GAClD,CAAC,EAA2B,yBAAyB,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EAE7G,EAAU,EAAmB,QAAQ,CAAY,EAEjD,EAAc,EAClB,EAAQ,GACR,EAAQ,MAAM,CAAC,EACf,CAAE,MAAK,SAAU,OAAQ,MAAO,EAAO,MAAO,KAAI,EAClD,CACF,EAEM,EAAc,MAAM,EAAgB,EAAK,EAA2B,yBAA2B,CAAC,CAAC,EAEnG,EAA6B,EAAa,SAE1C,EAAY,SAAW,EAEhB,EAAY,YAAc,EACnC,EAAe,EAAa,oBACnB,EAAY,aAAe,EAA2B,iBAAmB,KAClF,EAAe,EAAa,sBACnB,EAAY,OAAO,OAAS,GAAqB,EAAY,OAAO,OAAS,EACtF,EAAe,EAAa,2BACnB,EAAY,QAAU,EAA2B,yBAAyB,QAAU,KAC7F,EAAe,EAAa,oCAR5B,EAAe,EAAa,cAW9B,EAAoB,CAClB,WAAY,QACZ,eACA,WAAY,EAAY,QAAU,IAAA,GAClC,MAAO,EAAO,MACd,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,YAAa,EAAY,YACzB,YAAa,EAAY,YACzB,YAAa,EAAY,OAAS,EAAI,EAAc,IAAA,EACtD,CAAC,CACH"}
1
+ {"version":3,"file":"stdio.js","names":[],"sources":["../../src/presets/stdio.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { z } from 'zod';\n\nimport { cleanWorkingDirectory, snapshotWorkingDirectory } from '../helpers/cleanWorkingDirectory.js';\nimport { judgeAgainstExpectations } from '../helpers/compareExpectedOutputFiles.js';\nimport { copyTestCaseFileInput } from '../helpers/copyTestCaseFileInput.js';\nimport { findEntryPointFile } from '../helpers/findEntryPointFile.js';\nimport { findLanguageDefinitionByPath } from '../helpers/findLanguageDefinitionByPath.js';\nimport { judgeByStaticAnalysis } from '../helpers/judgeByStaticAnalysis.js';\nimport { parseArgs } from '../helpers/parseArgs.js';\nimport { printTestCaseResult } from '../helpers/printTestCaseResult.js';\nimport { readOutputFiles } from '../helpers/readOutputFiles.js';\nimport { makeAccessibleToSandboxUser, makeTraversableBySandboxUser } from '../helpers/sandboxUser.js';\nimport {\n judgesTestCasesWithoutExpectations,\n readProblemMarkdownFrontMatter,\n} from '../helpers/readProblemMarkdownFrontMatter.js';\nimport { readTestCases } from '../helpers/readTestCases.js';\nimport { spawnSyncWithTimeout } from '../helpers/spawnSyncWithTimeout.js';\nimport {\n copyProblemDirToTemporaryRoot,\n forciblyRemoveDirectory,\n forciblyRemoveDirectorySync,\n} from '../helpers/temporaryProblemDirCopy.js';\nimport { DecisionCode } from '../types/decisionCode.js';\n\nconst BUILD_TIMEOUT_SECONDS = 10;\nconst JUDGE_DEFAULT_TIMEOUT_SECONDS = 2;\nconst DEBUG_DEFAULT_TIMEOUT_SECONDS = 10;\n\nconst MAX_STDOUT_LENGTH = 50_000;\n// The judge server shows a test case on the problem page when its id contains `example`.\nconst EXAMPLE_TEST_CASE_ID_PATTERN = /example/;\n\nconst judgeParamsSchema = z.object({\n language: z.union([z.string(), z.array(z.string())]).optional(),\n});\n\nconst debugParamsSchema = judgeParamsSchema.extend({\n stdin: z.string().optional(),\n});\n\ntype DebugParams = z.infer<typeof debugParamsSchema>;\n\n/**\n * A preset judge function using stdin and stdout as test cases.\n *\n * A standard stdio problem must NOT commit a `judge.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `judge.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `judge.ts`:\n * ```bash\n * bun x exercode-problem judge model_answers/java\n * ```\n *\n * Run with the optional parameters:\n * ```bash\n * bun x exercode-problem judge model_answers/java '{ \"language\": \"javascript\" }'\n * ```\n */\nexport async function stdioJudgePreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = judgeParamsSchema.parse(args.params);\n\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(args.cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n\n // Without an expectation, a case would accept any run; only custom harnesses may judge input-only\n // cases. A problem judged by manual scoring or the presence of required output files has an\n // expectation of its own. Checked before the static analysis so that an authoring error surfaces\n // regardless of the submission.\n if (!judgesTestCasesWithoutExpectations(problemMarkdownFrontMatter)) {\n for (const testCase of testCases) {\n if (testCase.output === undefined && !(await hasExpectedFiles(testCase.fileOutputPath))) {\n throw new Error(\n `test case ${testCase.id} needs an expected output (${testCase.id}.out or a non-empty ${testCase.id}.fout/)`\n );\n }\n }\n }\n\n const staticAnalysisTestCaseResult = await judgeByStaticAnalysis(args.cwd, problemMarkdownFrontMatter);\n if (staticAnalysisTestCaseResult) {\n printTestCaseResult({ testCaseId: testCases[0]?.id ?? 'prebuild', ...staticAnalysisTestCaseResult });\n return;\n }\n\n const originalMainFilePath = await findEntryPointFile(args.cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(args.cwd);\n prebuiltMainFilePath = await findEntryPointFile(args.cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd: args.cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: testCases[0]?.id ?? 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const cwdSnapshot = await snapshotWorkingDirectory(args.cwd);\n\n if (testCases.length === 0) {\n printTestCaseResult({ testCaseId: 'default', decisionCode: DecisionCode.ACCEPTED });\n }\n\n for (const testCase of testCases) {\n // prepare test case\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, args.cwd);\n if (testCase.fileInputPath) await copyTestCaseFileInput(testCase.fileInputPath, args.cwd);\n\n // run\n const timeoutSeconds =\n typeof problemMarkdownFrontMatter.timeLimitMs === 'number'\n ? problemMarkdownFrontMatter.timeLimitMs / 1000\n : JUDGE_DEFAULT_TIMEOUT_SECONDS;\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd: args.cwd, encoding: 'utf8', input: testCase.input, env },\n timeoutSeconds\n );\n\n let outputFiles = await readOutputFiles(args.cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n // calculate decision\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n let judgementError: string | undefined;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n } else {\n try {\n const judgement = await judgeAgainstExpectations({\n stdout: spawnResult.stdout,\n expectedStdout: testCase.output,\n fileOutputPath: testCase.fileOutputPath,\n cwd: args.cwd,\n outputFiles,\n });\n if (!judgement.matches) decisionCode = DecisionCode.WRONG_ANSWER;\n outputFiles = judgement.outputFiles;\n } catch (error) {\n // An authoring error (e.g. an oversized expected file) is reported per case, like the command preset does.\n decisionCode = DecisionCode.RUNTIME_ERROR;\n judgementError = error instanceof Error ? error.message : String(error);\n }\n }\n\n printTestCaseResult({\n testCaseId: testCase.id,\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: testCase.input,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: (judgementError ?? spawnResult.stderr).slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n\n // clean up\n await cleanWorkingDirectory(args.cwd, cwdSnapshot);\n\n if (decisionCode !== DecisionCode.ACCEPTED) break;\n }\n}\n\nasync function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boolean> {\n if (fileOutputPath === undefined) return false;\n const dirents = await fs.promises.readdir(fileOutputPath, { withFileTypes: true, recursive: true });\n return dirents.some((dirent) => dirent.isFile());\n}\n\n/**\n * A preset debug function using stdin and stdout as test cases. The answer directory is copied to a\n * temporary directory where it is built and run together with `_shared.fin/` and the first example\n * case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.\n *\n * A standard stdio problem must NOT commit a `debug.ts` that only calls this preset: the Exercode\n * server applies this preset automatically when `debug.ts` is absent, and committed copies would\n * drift from the server's defaults.\n *\n * @example\n * Run in a problem directory without `debug.ts`:\n * ```bash\n * bun x exercode-problem debug model_answers/java '{ \"stdin\": \"1 2\" }'\n * ```\n */\nexport async function stdioDebugPreset(problemDir: string): Promise<void> {\n const args = parseArgs(process.argv);\n if (!args.cwd) throw new Error('cwd argument required');\n const params = debugParamsSchema.parse(args.params);\n\n // Everything (build, input files, run) happens in a disposable copy of the answer directory, so\n // the developer's files are never touched and whatever the submission leaves behind goes with it.\n // The copy keeps the directory hierarchy and links every ancestor `node_modules`, so packages the\n // answer resolves from its parents still resolve.\n // A terminated debug run must not leave the copy behind; `finally` does not run on a signal, so\n // the handlers learn the root as soon as it is created and stay until it is removed.\n let tempRoot: string | undefined;\n const removeOnSignal = (): void => {\n if (tempRoot !== undefined) forciblyRemoveDirectorySync(tempRoot);\n process.exit(1);\n };\n process.once('SIGINT', removeOnSignal);\n process.once('SIGTERM', removeOnSignal);\n try {\n const copy = await copyProblemDirToTemporaryRoot(args.cwd, { onTempRootCreated: (root) => (tempRoot = root) });\n // `mkdtemp` creates a 0700 root: the sandbox user only traverses the root and the synthesized\n // ancestors, and gets full access to the copied answer directory alone.\n makeTraversableBySandboxUser(copy.tempRoot, path.dirname(copy.copiedProblemDir));\n await debugInTemporaryCopy(problemDir, copy.copiedProblemDir, params);\n } finally {\n if (tempRoot !== undefined) await forciblyRemoveDirectory(tempRoot);\n process.off('SIGINT', removeOnSignal);\n process.off('SIGTERM', removeOnSignal);\n }\n}\n\nasync function debugInTemporaryCopy(problemDir: string, cwd: string, params: DebugParams): Promise<void> {\n // The sandboxed submission must read its sources and write build/run outputs in its directory.\n makeAccessibleToSandboxUser(cwd);\n\n const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);\n\n const originalMainFilePath = await findEntryPointFile(cwd, params.language);\n if (!originalMainFilePath) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.MISSING_REQUIRED_SUBMISSION_FILE_ERROR,\n stderr: `main file not found${params.language ? `: language: ${params.language}` : ''}`,\n });\n return;\n }\n\n const languageDefinition = findLanguageDefinitionByPath(originalMainFilePath);\n if (!languageDefinition) {\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.WRONG_ANSWER,\n stderr: 'unsupported language',\n });\n return;\n }\n\n // `CI` changes affects Chainlit. `FORCE_COLOR` affects Bun.\n const env = { ...process.env, CI: '', FORCE_COLOR: '0' };\n\n let prebuiltMainFilePath: string | undefined;\n\n if (languageDefinition.prebuild) {\n try {\n await languageDefinition.prebuild(cwd);\n prebuiltMainFilePath = await findEntryPointFile(cwd, params.language);\n } catch (error) {\n console.error('prebuild error', error);\n\n printTestCaseResult({\n testCaseId: 'prebuild',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n const mainFilePath = prebuiltMainFilePath ?? originalMainFilePath;\n\n if (languageDefinition.buildCommand) {\n try {\n const buildCommand = languageDefinition.buildCommand(mainFilePath);\n\n const buildSpawnResult = spawnSyncWithTimeout(\n buildCommand[0],\n buildCommand.slice(1),\n { cwd, encoding: 'utf8', env },\n BUILD_TIMEOUT_SECONDS\n );\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (buildSpawnResult.status !== 0) {\n decisionCode = DecisionCode.BUILD_ERROR;\n } else if (buildSpawnResult.timeSeconds > BUILD_TIMEOUT_SECONDS) {\n decisionCode = DecisionCode.BUILD_TIME_LIMIT_EXCEEDED;\n } else if (\n buildSpawnResult.stdout.length > MAX_STDOUT_LENGTH ||\n buildSpawnResult.stderr.length > MAX_STDOUT_LENGTH\n ) {\n decisionCode = DecisionCode.BUILD_OUTPUT_SIZE_LIMIT_EXCEEDED;\n }\n\n if (decisionCode !== DecisionCode.ACCEPTED) {\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode,\n exitStatus: buildSpawnResult.status ?? undefined,\n stdout: buildSpawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: buildSpawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: buildSpawnResult.timeSeconds,\n memoryBytes: buildSpawnResult.memoryBytes,\n });\n return;\n }\n } catch (error) {\n console.error('build error', error);\n\n printTestCaseResult({\n testCaseId: 'build',\n decisionCode: DecisionCode.BUILD_ERROR,\n stderr: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n }\n\n // A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the\n // first example case (the cases a learner may see), placed the way the judge does. Hidden cases'\n // input files are never handed to learner code.\n const testCases = await readTestCases(path.join(problemDir, 'test_cases'));\n if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);\n const exampleFileInputPath = testCases.find(\n (testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath\n )?.fileInputPath;\n if (exampleFileInputPath) {\n await copyTestCaseFileInput(exampleFileInputPath, cwd);\n } else if (testCases.some((testCase) => testCase.fileInputPath)) {\n console.error('debug: no example test case has input files, so the program runs without them');\n }\n\n const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);\n\n const command = languageDefinition.command(mainFilePath);\n\n const spawnResult = spawnSyncWithTimeout(\n command[0],\n command.slice(1),\n { cwd, encoding: 'utf8', input: params.stdin, env },\n timeoutSeconds\n );\n\n const outputFiles = await readOutputFiles(cwd, problemMarkdownFrontMatter.requiredOutputFilePaths ?? []);\n\n let decisionCode: DecisionCode = DecisionCode.ACCEPTED;\n\n if (spawnResult.status !== 0) {\n decisionCode = DecisionCode.RUNTIME_ERROR;\n } else if (spawnResult.timeSeconds > timeoutSeconds) {\n decisionCode = DecisionCode.TIME_LIMIT_EXCEEDED;\n } else if (spawnResult.memoryBytes > (problemMarkdownFrontMatter.memoryLimitByte ?? Number.POSITIVE_INFINITY)) {\n decisionCode = DecisionCode.MEMORY_LIMIT_EXCEEDED;\n } else if (spawnResult.stdout.length > MAX_STDOUT_LENGTH || spawnResult.stderr.length > MAX_STDOUT_LENGTH) {\n decisionCode = DecisionCode.OUTPUT_SIZE_LIMIT_EXCEEDED;\n } else if (outputFiles.length < (problemMarkdownFrontMatter.requiredOutputFilePaths?.length ?? 0)) {\n decisionCode = DecisionCode.MISSING_REQUIRED_OUTPUT_FILE_ERROR;\n }\n\n printTestCaseResult({\n testCaseId: 'debug',\n decisionCode,\n exitStatus: spawnResult.status ?? undefined,\n stdin: params.stdin,\n stdout: spawnResult.stdout.slice(0, MAX_STDOUT_LENGTH) || undefined,\n stderr: spawnResult.stderr.slice(0, MAX_STDOUT_LENGTH) || undefined,\n timeSeconds: spawnResult.timeSeconds,\n memoryBytes: spawnResult.memoryBytes,\n outputFiles: outputFiles.length > 0 ? outputFiles : undefined,\n });\n}\n"],"mappings":"4zCA4BA,MAIM,EAAoB,IAEpB,EAA+B,UAE/B,EAAoB,EAAE,OAAO,CACjC,SAAU,EAAE,MAAM,CAAC,EAAE,OAAO,EAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAChE,CAAC,EAEK,EAAoB,EAAkB,OAAO,CACjD,MAAO,EAAE,OAAO,CAAC,CAAC,SAAS,CAC7B,CAAC,EAsBD,eAAsB,EAAiB,EAAmC,CACxE,IAAM,EAAO,EAAU,QAAQ,IAAI,EACnC,GAAI,CAAC,EAAK,IAAK,MAAU,MAAM,uBAAuB,EACtD,IAAM,EAAS,EAAkB,MAAM,EAAK,MAAM,EAGlD,EAA4B,EAAK,GAAG,EAEpC,IAAM,EAA6B,MAAM,EAA+B,CAAU,EAC5E,EAAY,MAAM,EAAc,EAAK,KAAK,EAAY,YAAY,CAAC,EAMzE,GAAI,CAAC,EAAmC,CAA0B,EAC3D,KAAA,IAAM,KAAY,EACrB,GAAI,EAAS,SAAW,IAAA,IAAa,CAAE,MAAM,EAAiB,EAAS,cAAc,EACnF,MAAU,MACR,aAAa,EAAS,GAAG,6BAA6B,EAAS,GAAG,sBAAsB,EAAS,GAAG,QACtG,CAAA,CAKN,IAAM,EAA+B,MAAM,EAAsB,EAAK,IAAK,CAA0B,EACrG,GAAI,EAA8B,CAChC,EAAoB,CAAE,WAAY,EAAU,EAAE,EAAE,IAAM,WAAY,GAAG,CAA6B,CAAC,EACnG,MACF,CAEA,IAAM,EAAuB,MAAM,EAAmB,EAAK,IAAK,EAAO,QAAQ,EAC/E,GAAI,CAAC,EAAsB,CACzB,EAAoB,CAClB,WAAY,EAAU,EAAE,EAAE,IAAM,WAChC,aAAc,EAAa,uCAC3B,OAAQ,sBAAsB,EAAO,SAAW,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B,EAAY,OAAO,OAAS,EACtF,EAAe,EAAa,2BACnB,EAAY,QAAU,EAA2B,yBAAyB,QAAU,KAC7F,EAAe,EAAa,oCAR5B,EAAe,EAAa,cAW9B,EAAoB,CAClB,WAAY,QACZ,eACA,WAAY,EAAY,QAAU,IAAA,GAClC,MAAO,EAAO,MACd,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,OAAQ,EAAY,OAAO,MAAM,EAAG,CAAiB,GAAK,IAAA,GAC1D,YAAa,EAAY,YACzB,YAAa,EAAY,YACzB,YAAa,EAAY,OAAS,EAAI,EAAc,IAAA,EACtD,CAAC,CACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exercode/problem-utils",
3
- "version": "2.4.0",
3
+ "version": "2.4.2",
4
4
  "description": ":100: A set of utilities for judging programs on Exercode (https://exercode.willbooster.com/).",
5
5
  "keywords": [
6
6
  "exercode",
@@ -53,11 +53,11 @@
53
53
  },
54
54
  "prettier": "@willbooster/prettier-config",
55
55
  "dependencies": {
56
- "@ai-sdk/amazon-bedrock": "5.0.61",
57
- "@ai-sdk/google": "4.0.50",
58
- "@ai-sdk/openai": "4.0.46",
59
- "@ai-sdk/xai": "4.0.43",
60
- "ai": "7.0.77",
56
+ "@ai-sdk/amazon-bedrock": "5.0.67",
57
+ "@ai-sdk/google": "4.0.57",
58
+ "@ai-sdk/openai": "4.0.51",
59
+ "@ai-sdk/xai": "4.0.49",
60
+ "ai": "7.0.84",
61
61
  "front-matter": "4.0.2",
62
62
  "zod": "4.4.3"
63
63
  },
@@ -67,16 +67,16 @@
67
67
  "@tsconfig/node-ts": "23.6.4",
68
68
  "@tsconfig/node24": "24.0.5",
69
69
  "@types/bun": "1.4.0",
70
- "@types/node": "26.2.0",
70
+ "@types/node": "26.4.0",
71
71
  "@willbooster/oxfmt-config": "1.2.2",
72
72
  "@willbooster/oxlint-config": "1.4.8",
73
73
  "@willbooster/prettier-config": "10.4.0",
74
- "@willbooster/wb": "22.1.2",
74
+ "@willbooster/wb": "22.1.3",
75
75
  "build-ts": "21.0.9",
76
76
  "conventional-changelog-conventionalcommits": "10.4.0",
77
- "lefthook": "2.1.10",
78
- "oxfmt": "0.64.0",
79
- "oxlint": "1.79.0",
77
+ "lefthook": "2.1.12",
78
+ "oxfmt": "0.65.0",
79
+ "oxlint": "1.80.0",
80
80
  "oxlint-tsgolint": "7.0.2001",
81
81
  "prettier": "3.9.6",
82
82
  "prettier-plugin-java": "2.10.3",