atcoder-workspace 1.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -0
  3. package/THIRD_PARTY_LICENSES +21 -0
  4. package/dist/atcoder/client.d.ts +2 -0
  5. package/dist/atcoder/client.js +23 -0
  6. package/dist/atcoder/new.d.ts +15 -0
  7. package/dist/atcoder/new.js +123 -0
  8. package/dist/atcoder/parser/contest-tasks.d.ts +6 -0
  9. package/dist/atcoder/parser/contest-tasks.js +86 -0
  10. package/dist/atcoder/parser/limits.d.ts +10 -0
  11. package/dist/atcoder/parser/limits.js +71 -0
  12. package/dist/atcoder/parser/problem-page.d.ts +12 -0
  13. package/dist/atcoder/parser/problem-page.js +136 -0
  14. package/dist/atcoder/parser/submission-status.d.ts +8 -0
  15. package/dist/atcoder/parser/submission-status.js +78 -0
  16. package/dist/atcoder/submit.d.ts +9 -0
  17. package/dist/atcoder/submit.js +182 -0
  18. package/dist/cli.d.ts +2 -0
  19. package/dist/cli.js +508 -0
  20. package/dist/config/config-store.d.ts +17 -0
  21. package/dist/config/config-store.js +92 -0
  22. package/dist/session/auth.d.ts +8 -0
  23. package/dist/session/auth.js +117 -0
  24. package/dist/session/store.d.ts +15 -0
  25. package/dist/session/store.js +75 -0
  26. package/dist/test-runner/diff.d.ts +7 -0
  27. package/dist/test-runner/diff.js +32 -0
  28. package/dist/test-runner/runner.d.ts +46 -0
  29. package/dist/test-runner/runner.js +274 -0
  30. package/dist/utils/errors.d.ts +15 -0
  31. package/dist/utils/errors.js +35 -0
  32. package/dist/utils/format.d.ts +9 -0
  33. package/dist/utils/format.js +89 -0
  34. package/dist/utils/i18n.d.ts +345 -0
  35. package/dist/utils/i18n.js +413 -0
  36. package/dist/utils/open.d.ts +8 -0
  37. package/dist/utils/open.js +50 -0
  38. package/dist/workspace/finder.d.ts +9 -0
  39. package/dist/workspace/finder.js +62 -0
  40. package/dist/workspace/initializer.d.ts +4 -0
  41. package/dist/workspace/initializer.js +109 -0
  42. package/package.json +38 -0
  43. package/src/atcoder/client.ts +21 -0
  44. package/src/atcoder/new.ts +107 -0
  45. package/src/atcoder/parser/contest-tasks.test.ts +37 -0
  46. package/src/atcoder/parser/contest-tasks.ts +61 -0
  47. package/src/atcoder/parser/limits.test.ts +52 -0
  48. package/src/atcoder/parser/limits.ts +75 -0
  49. package/src/atcoder/parser/problem-page.test.ts +68 -0
  50. package/src/atcoder/parser/problem-page.ts +126 -0
  51. package/src/atcoder/parser/submission-status.test.ts +36 -0
  52. package/src/atcoder/parser/submission-status.ts +54 -0
  53. package/src/atcoder/submit.ts +170 -0
  54. package/src/cli.ts +554 -0
  55. package/src/config/config-store.ts +72 -0
  56. package/src/session/auth.ts +87 -0
  57. package/src/session/store.ts +50 -0
  58. package/src/test-runner/diff.test.ts +26 -0
  59. package/src/test-runner/diff.ts +42 -0
  60. package/src/test-runner/runner.test.ts +70 -0
  61. package/src/test-runner/runner.ts +315 -0
  62. package/src/utils/errors.ts +31 -0
  63. package/src/utils/format.test.ts +69 -0
  64. package/src/utils/format.ts +95 -0
  65. package/src/utils/i18n.test.ts +74 -0
  66. package/src/utils/i18n.ts +418 -0
  67. package/src/utils/open.ts +47 -0
  68. package/src/workspace/finder.ts +29 -0
  69. package/src/workspace/initializer.ts +85 -0
  70. package/tsconfig.json +16 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dakoyo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # AtCoder Workspace (atc)
2
+
3
+ **Node.js と TypeScript で開発された、ローカルファーストの AtCoder 向け CLI ツールです。**
4
+
5
+ AtCoder Workspace は、テンプレート、ログイン状態、テストケースなどをすべてワークスペース内で完結して管理するよう設計されています。グローバル環境を汚さず、どの環境でも同じ設定をそのまま利用できます。
6
+
7
+
8
+ ## インストール
9
+
10
+ npm を利用してグローバルインストールします。
11
+
12
+ ```bash
13
+ npm install -g atcoder-workspace
14
+ ```
15
+
16
+ ---
17
+
18
+ ## コマンド一覧
19
+
20
+ ### ワークスペース・セッション管理
21
+
22
+ ```bash
23
+ atc init # .atcoder-cli/ の初期構成と .gitignore を作成
24
+ atc login # REVEL_SESSION Cookie を入力してログイン
25
+ atc whoami # 現在ログイン中のユーザー名を表示
26
+ atc logout # 保存されているセッション情報を削除
27
+ ```
28
+
29
+ ### 問題取得・テスト・提出
30
+
31
+ ```bash
32
+ atc new <contest> [task] # 問題文・サンプルケースを取得し、テンプレート付きで作業ディレクトリを作成
33
+ atc new <contest> --all # コンテスト内の全問題を一括で作成
34
+ atc test [task] [file] # ローカルのサンプルケースでコンパイル・実行してテスト
35
+ atc submit [task] [file] # ローカルテストを実施し、確認後に提出・ジャッジ結果を取得
36
+ ```
37
+
38
+ ---
39
+
40
+ ## ワークスペース構成
41
+
42
+ 初期化すると、ワークスペースは次のような構成になります。
43
+
44
+ ```text
45
+ my-atcoder-workspace/
46
+ ├── .atcoder-cli/
47
+ │ ├── config.json # 言語ごとのビルド・実行設定
48
+ │ ├── session.json # ログインセッション(自動で .gitignore に追加)
49
+ │ └── templates/ # カスタムテンプレート(例: templates/cpp/main.cpp)
50
+ ├── .gitignore
51
+ ├── abc300/ # 作成されたコンテストフォルダ
52
+ │ ├── a/
53
+ │ │ ├── main.cpp
54
+ │ │ └── tests/ # サンプル入力・出力(sample-1.in, sample-1.out など)
55
+ │ └── b/
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 設定ファイル(`.atcoder-cli/config.json`)
61
+
62
+ デフォルトの設定ファイルでは、使用する言語やビルド・実行コマンド、テンプレート、テストディレクトリなどを自由にカスタマイズできます。
63
+
64
+ ```json
65
+ {
66
+ "defaultLanguage": "cpp",
67
+ "languages": {
68
+ "cpp": {
69
+ "extension": "cpp",
70
+ "templateDir": "templates/cpp",
71
+ "build": "g++ -O2 -std=gnu++20 -o a.out main.cpp",
72
+ "run": "./a.out"
73
+ },
74
+ "python": {
75
+ "extension": "py",
76
+ "templateDir": "templates/python",
77
+ "build": "",
78
+ "run": "python3 main.py"
79
+ }
80
+ },
81
+ "testDirName": "tests"
82
+ }
83
+ ```
84
+
85
+ ---
86
+
87
+ ## 謝辞
88
+
89
+ AtCoder Workspace は、以下のプロジェクトに着想を得ています。
90
+
91
+ * **atcoder-cli (acc)**(開発者: Tatamo)
92
+ * **online-judge-tools (oj)**(online-judge-tools Organization)
93
+
94
+ 各ライセンスの詳細については、`THIRD_PARTY_LICENSES` をご覧ください。
95
+
96
+ ## ライセンス
97
+
98
+ MIT License
@@ -0,0 +1,21 @@
1
+ # Third Party Acknowledgements
2
+
3
+ AtCoder Workspace is a modern, single-directory all-in-one CLI for AtCoder. We would like to express our deepest gratitude to the creators and maintainers of the following projects, whose design and features inspired this CLI:
4
+
5
+ ## 1. atcoder-cli (acc)
6
+ - **Author**: Tatamo
7
+ - **Repository**: https://github.com/tatamo/atcoder-cli
8
+ - **License**: MIT License
9
+ - **Acknowledge**: We took inspiration from `atcoder-cli`'s template configurations, task structures, and workspace setups.
10
+
11
+ ---
12
+
13
+ ## 2. online-judge-tools (oj)
14
+ - **Organization**: online-judge-tools
15
+ - **Repository**: https://github.com/online-judge-tools/oj
16
+ - **License**: MIT License
17
+ - **Acknowledge**: We took inspiration from `online-judge-tools`'s test execution runner, diff normalization algorithms, and command interface structure.
18
+
19
+ ---
20
+
21
+ Thank you for paving the way for the competitive programming tooling ecosystem!
@@ -0,0 +1,2 @@
1
+ import { AxiosInstance } from 'axios';
2
+ export declare function createAtCoderClient(workspaceRoot: string): AxiosInstance;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createAtCoderClient = createAtCoderClient;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const store_1 = require("../session/store");
9
+ function createAtCoderClient(workspaceRoot) {
10
+ const cookies = (0, store_1.loadSession)(workspaceRoot);
11
+ const headers = {
12
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
13
+ };
14
+ if (cookies) {
15
+ headers['Cookie'] = (0, store_1.getCookieHeaderString)(cookies);
16
+ }
17
+ const client = axios_1.default.create({
18
+ baseURL: 'https://atcoder.jp',
19
+ headers,
20
+ timeout: 15000,
21
+ });
22
+ return client;
23
+ }
@@ -0,0 +1,15 @@
1
+ import { TaskInfo } from './parser/contest-tasks';
2
+ export interface SetupResult {
3
+ contestId: string;
4
+ taskLabel: string;
5
+ taskDir: string;
6
+ sampleCount: number;
7
+ }
8
+ /**
9
+ * Fetches the list of tasks for a given contest.
10
+ */
11
+ export declare function fetchContestTasks(workspaceRoot: string, contestId: string): Promise<TaskInfo[]>;
12
+ /**
13
+ * Sets up a single task by downloading sample cases and copying language templates.
14
+ */
15
+ export declare function setupTask(workspaceRoot: string, contestId: string, task: TaskInfo, languageKey?: string): Promise<SetupResult>;
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.fetchContestTasks = fetchContestTasks;
37
+ exports.setupTask = setupTask;
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const client_1 = require("./client");
41
+ const contest_tasks_1 = require("./parser/contest-tasks");
42
+ const problem_page_1 = require("./parser/problem-page");
43
+ const config_store_1 = require("../config/config-store");
44
+ const errors_1 = require("../utils/errors");
45
+ /**
46
+ * Fetches the list of tasks for a given contest.
47
+ */
48
+ async function fetchContestTasks(workspaceRoot, contestId) {
49
+ const client = (0, client_1.createAtCoderClient)(workspaceRoot);
50
+ try {
51
+ const res = await client.get(`/contests/${contestId}/tasks`);
52
+ return (0, contest_tasks_1.parseContestTasks)(res.data);
53
+ }
54
+ catch (err) {
55
+ throw new errors_1.AtcError(`Failed to fetch tasks for contest "${contestId}": ${err.message}`);
56
+ }
57
+ }
58
+ /**
59
+ * Sets up a single task by downloading sample cases and copying language templates.
60
+ */
61
+ async function setupTask(workspaceRoot, contestId, task, languageKey) {
62
+ const config = (0, config_store_1.loadConfig)(workspaceRoot);
63
+ const langKey = languageKey || config.defaultLanguage;
64
+ const langConfig = config.languages[langKey];
65
+ if (!langConfig) {
66
+ throw new errors_1.AtcError(`Language configuration for "${langKey}" not found in config.json`);
67
+ }
68
+ // Create contest and task directories
69
+ const contestParentDir = config.contestDir ? path.join(workspaceRoot, config.contestDir) : workspaceRoot;
70
+ const contestDir = path.join(contestParentDir, contestId);
71
+ const taskDir = path.join(contestDir, task.label);
72
+ if (!fs.existsSync(taskDir)) {
73
+ fs.mkdirSync(taskDir, { recursive: true });
74
+ }
75
+ // Copy template files
76
+ const templateSrcDir = path.join(workspaceRoot, '.atcoder-cli', langConfig.templateDir);
77
+ if (fs.existsSync(templateSrcDir) && fs.statSync(templateSrcDir).isDirectory()) {
78
+ const files = fs.readdirSync(templateSrcDir);
79
+ for (const file of files) {
80
+ const srcPath = path.join(templateSrcDir, file);
81
+ const destPath = path.join(taskDir, file);
82
+ if (fs.statSync(srcPath).isFile() && !fs.existsSync(destPath)) {
83
+ fs.copyFileSync(srcPath, destPath);
84
+ }
85
+ }
86
+ }
87
+ // Fetch problem page
88
+ const client = (0, client_1.createAtCoderClient)(workspaceRoot);
89
+ let problemHtml = '';
90
+ try {
91
+ const res = await client.get(`/contests/${contestId}/tasks/${task.id}`);
92
+ problemHtml = res.data;
93
+ }
94
+ catch (err) {
95
+ throw new errors_1.AtcError(`Failed to fetch problem page for "${task.id}": ${err.message}`);
96
+ }
97
+ const problemDetails = (0, problem_page_1.parseProblemPage)(problemHtml);
98
+ // Write sample cases to tests/ directory
99
+ const testDirName = config.testDirName || 'tests';
100
+ const testDir = path.join(taskDir, testDirName);
101
+ if (fs.existsSync(testDir)) {
102
+ // Clear existing sample files to avoid mixing old/new samples
103
+ const files = fs.readdirSync(testDir);
104
+ for (const file of files) {
105
+ if (file.startsWith('sample-')) {
106
+ fs.unlinkSync(path.join(testDir, file));
107
+ }
108
+ }
109
+ }
110
+ else {
111
+ fs.mkdirSync(testDir, { recursive: true });
112
+ }
113
+ for (const sample of problemDetails.samples) {
114
+ fs.writeFileSync(path.join(testDir, `sample-${sample.index}.in`), sample.input, 'utf8');
115
+ fs.writeFileSync(path.join(testDir, `sample-${sample.index}.out`), sample.output, 'utf8');
116
+ }
117
+ return {
118
+ contestId,
119
+ taskLabel: task.label,
120
+ taskDir,
121
+ sampleCount: problemDetails.samples.length
122
+ };
123
+ }
@@ -0,0 +1,6 @@
1
+ export interface TaskInfo {
2
+ id: string;
3
+ label: string;
4
+ url: string;
5
+ }
6
+ export declare function parseContestTasks(html: string): TaskInfo[];
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.parseContestTasks = parseContestTasks;
37
+ const cheerio = __importStar(require("cheerio"));
38
+ function parseContestTasks(html) {
39
+ const $ = cheerio.load(html);
40
+ const tasks = [];
41
+ const seenIds = new Set();
42
+ $('a').each((_, elem) => {
43
+ const href = $(elem).attr('href');
44
+ if (href) {
45
+ const match = href.match(/\/contests\/([^/]+)\/tasks\/([^/?#]+)$/);
46
+ if (match) {
47
+ const id = match[2];
48
+ const label = $(elem).text().trim().toLowerCase();
49
+ if (label.length > 0 && label.length <= 4 && !seenIds.has(id)) {
50
+ seenIds.add(id);
51
+ tasks.push({
52
+ id,
53
+ label,
54
+ url: href
55
+ });
56
+ }
57
+ }
58
+ }
59
+ });
60
+ if (tasks.length === 0) {
61
+ $('a').each((_, elem) => {
62
+ const href = $(elem).attr('href');
63
+ if (href) {
64
+ const match = href.match(/\/contests\/([^/]+)\/tasks\/([^/?#]+)$/);
65
+ if (match) {
66
+ const id = match[2];
67
+ const label = $(elem).text().trim().toLowerCase();
68
+ if (label && !seenIds.has(id)) {
69
+ seenIds.add(id);
70
+ let cleanLabel = label;
71
+ if (cleanLabel.length > 4) {
72
+ const parts = id.split('_');
73
+ cleanLabel = parts[parts.length - 1] || 'task';
74
+ }
75
+ tasks.push({
76
+ id,
77
+ label: cleanLabel.toLowerCase(),
78
+ url: href
79
+ });
80
+ }
81
+ }
82
+ }
83
+ });
84
+ }
85
+ return tasks.sort((a, b) => a.label.localeCompare(b.label));
86
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Parses a time limit string and returns the limit in milliseconds.
3
+ * E.g., "2 sec", "2.5 sec", "2000 ms", "2 秒", "2.5 秒"
4
+ */
5
+ export declare function parseTimeLimit(text: string): number;
6
+ /**
7
+ * Parses a memory limit string and returns the limit in bytes.
8
+ * E.g., "1024 MB", "1024 MiB", "256 KB", "256 KiB", "1 GB", "1 GiB"
9
+ */
10
+ export declare function parseMemoryLimit(text: string): number;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTimeLimit = parseTimeLimit;
4
+ exports.parseMemoryLimit = parseMemoryLimit;
5
+ const errors_1 = require("../../utils/errors");
6
+ /**
7
+ * Parses a time limit string and returns the limit in milliseconds.
8
+ * E.g., "2 sec", "2.5 sec", "2000 ms", "2 秒", "2.5 秒"
9
+ */
10
+ function parseTimeLimit(text) {
11
+ // Support both English and Japanese formats
12
+ const timeRegex = /(?:Time Limit|実行時間制限)\s*:\s*([\d.]+)\s*(sec|ms|秒|ミリ秒)/i;
13
+ const match = text.match(timeRegex);
14
+ if (!match) {
15
+ // If not found with label, try parsing raw units in the context of limits
16
+ const simpleRegex = /(\d+(?:\.\d+)?)\s*(sec|ms|秒|ミリ秒)/i;
17
+ const simpleMatch = text.match(simpleRegex);
18
+ if (!simpleMatch) {
19
+ throw new errors_1.ParseError(`Could not parse time limit from text: "${text}"`);
20
+ }
21
+ return convertTimeToMs(parseFloat(simpleMatch[1]), simpleMatch[2]);
22
+ }
23
+ const value = parseFloat(match[1]);
24
+ const unit = match[2];
25
+ return convertTimeToMs(value, unit);
26
+ }
27
+ function convertTimeToMs(value, unit) {
28
+ const normUnit = unit.toLowerCase();
29
+ if (normUnit === 'sec' || normUnit === '秒') {
30
+ return Math.round(value * 1000);
31
+ }
32
+ if (normUnit === 'ms' || normUnit === 'ミリ秒') {
33
+ return Math.round(value);
34
+ }
35
+ throw new errors_1.ParseError(`Unknown time unit: "${unit}"`);
36
+ }
37
+ /**
38
+ * Parses a memory limit string and returns the limit in bytes.
39
+ * E.g., "1024 MB", "1024 MiB", "256 KB", "256 KiB", "1 GB", "1 GiB"
40
+ */
41
+ function parseMemoryLimit(text) {
42
+ const memoryRegex = /(?:Memory Limit|メモリ制限)\s*:\s*(\d+)\s*(KB|MB|GB|KiB|MiB|GiB)/i;
43
+ const match = text.match(memoryRegex);
44
+ if (!match) {
45
+ const simpleRegex = /(\d+)\s*(KB|MB|GB|KiB|MiB|GiB)/i;
46
+ const simpleMatch = text.match(simpleRegex);
47
+ if (!simpleMatch) {
48
+ throw new errors_1.ParseError(`Could not parse memory limit from text: "${text}"`);
49
+ }
50
+ return convertMemoryToBytes(parseInt(simpleMatch[1], 10), simpleMatch[2]);
51
+ }
52
+ const value = parseInt(match[1], 10);
53
+ const unit = match[2];
54
+ return convertMemoryToBytes(value, unit);
55
+ }
56
+ function convertMemoryToBytes(value, unit) {
57
+ const normUnit = unit.toLowerCase();
58
+ switch (normUnit) {
59
+ case 'kb':
60
+ case 'kib':
61
+ return value * 1024;
62
+ case 'mb':
63
+ case 'mib':
64
+ return value * 1024 * 1024;
65
+ case 'gb':
66
+ case 'gib':
67
+ return value * 1024 * 1024 * 1024;
68
+ default:
69
+ throw new errors_1.ParseError(`Unknown memory unit: "${unit}"`);
70
+ }
71
+ }
@@ -0,0 +1,12 @@
1
+ export interface SampleCase {
2
+ index: number;
3
+ input: string;
4
+ output: string;
5
+ }
6
+ export interface TaskDetails {
7
+ title: string;
8
+ timeLimitMs: number;
9
+ memoryLimitBytes: number;
10
+ samples: SampleCase[];
11
+ }
12
+ export declare function parseProblemPage(html: string): TaskDetails;
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.parseProblemPage = parseProblemPage;
37
+ const cheerio = __importStar(require("cheerio"));
38
+ const limits_1 = require("./limits");
39
+ function parseProblemPage(html) {
40
+ const $ = cheerio.load(html);
41
+ let title = $('span.h2').first().text().trim();
42
+ if (!title) {
43
+ title = $('h2').first().text().trim();
44
+ }
45
+ if (!title) {
46
+ title = $('title').text().trim() || 'Task';
47
+ }
48
+ title = title.replace(/\s+/g, ' ');
49
+ const taskStatementText = $('#task-statement').text() || $('body').text();
50
+ let timeLimitMs = 2000;
51
+ let memoryLimitBytes = 1024 * 1024 * 1024;
52
+ try {
53
+ timeLimitMs = (0, limits_1.parseTimeLimit)(taskStatementText);
54
+ }
55
+ catch (e) {
56
+ try {
57
+ timeLimitMs = (0, limits_1.parseTimeLimit)($('body').text());
58
+ }
59
+ catch (err) {
60
+ console.warn('Could not parse time limit. Using default 2000ms.');
61
+ }
62
+ }
63
+ try {
64
+ memoryLimitBytes = (0, limits_1.parseMemoryLimit)(taskStatementText);
65
+ }
66
+ catch (e) {
67
+ try {
68
+ memoryLimitBytes = (0, limits_1.parseMemoryLimit)($('body').text());
69
+ }
70
+ catch (err) {
71
+ console.warn('Could not parse memory limit. Using default 1024MB.');
72
+ }
73
+ }
74
+ let $container = $('#task-statement');
75
+ if ($container.find('.lang-en').length > 0) {
76
+ $container = $container.find('.lang-en');
77
+ }
78
+ else if ($container.find('.lang-ja').length > 0) {
79
+ $container = $container.find('.lang-ja');
80
+ }
81
+ const sampleMap = {};
82
+ const inputRegex = /(?:Sample\s+Input|入力例)\s*(?:#|No\.?)?\s*(\d+)/i;
83
+ const outputRegex = /(?:Sample\s+Output|出力例)\s*(?:#|No\.?)?\s*(\d+)/i;
84
+ $container.find('h3, h4').each((_, elem) => {
85
+ const headerText = $(elem).text().trim();
86
+ const inputMatch = headerText.match(inputRegex);
87
+ const outputMatch = headerText.match(outputRegex);
88
+ if (inputMatch || outputMatch) {
89
+ const isInput = !!inputMatch;
90
+ const index = parseInt(isInput ? inputMatch[1] : outputMatch[1], 10);
91
+ let $pre = $(elem).next('pre');
92
+ if ($pre.length === 0) {
93
+ $pre = $(elem).parent().find('pre');
94
+ }
95
+ if ($pre.length === 0 || $pre.parent().is(elem)) {
96
+ $pre = $(elem).nextAll('pre').first();
97
+ }
98
+ if ($pre.length === 0) {
99
+ $pre = $(elem).nextAll().find('pre').first();
100
+ }
101
+ if ($pre.length > 0) {
102
+ let content = $pre.text();
103
+ content = content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
104
+ if (content && !content.endsWith('\n')) {
105
+ content += '\n';
106
+ }
107
+ if (!sampleMap[index]) {
108
+ sampleMap[index] = {};
109
+ }
110
+ if (isInput) {
111
+ sampleMap[index].input = content;
112
+ }
113
+ else {
114
+ sampleMap[index].output = content;
115
+ }
116
+ }
117
+ }
118
+ });
119
+ const samples = Object.keys(sampleMap)
120
+ .map(key => {
121
+ const idx = parseInt(key, 10);
122
+ return {
123
+ index: idx,
124
+ input: sampleMap[idx].input ?? '',
125
+ output: sampleMap[idx].output ?? ''
126
+ };
127
+ })
128
+ .filter(s => s.input !== '' || s.output !== '')
129
+ .sort((a, b) => a.index - b.index);
130
+ return {
131
+ title,
132
+ timeLimitMs,
133
+ memoryLimitBytes,
134
+ samples
135
+ };
136
+ }
@@ -0,0 +1,8 @@
1
+ export interface SubmissionStatus {
2
+ status: string;
3
+ time?: string;
4
+ memory?: string;
5
+ score?: string;
6
+ isCompleted: boolean;
7
+ }
8
+ export declare function parseSubmissionStatus(html: string): SubmissionStatus;