@eliceio/cdk-cli 0.0.0-stage → 0.1.0-alpha.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 (128) hide show
  1. package/README.md +511 -2
  2. package/es/bin/index.d.ts +2 -0
  3. package/es/bin/index.js +10 -0
  4. package/es/cli.d.ts +5 -0
  5. package/es/cli.js +171 -0
  6. package/es/commands/build/index.d.ts +27 -0
  7. package/es/commands/build/index.js +154 -0
  8. package/es/commands/check/index.d.ts +9 -0
  9. package/es/commands/check/index.js +31 -0
  10. package/es/commands/create/index.d.ts +8 -0
  11. package/es/commands/create/index.js +22 -0
  12. package/es/commands/create/scaffold.d.ts +24 -0
  13. package/es/commands/create/scaffold.js +82 -0
  14. package/es/commands/dev/index.d.ts +6 -0
  15. package/es/commands/dev/index.js +40 -0
  16. package/es/commands/doctor/index.d.ts +33 -0
  17. package/es/commands/doctor/index.js +230 -0
  18. package/es/core/collect.d.ts +21 -0
  19. package/es/core/collect.js +89 -0
  20. package/es/core/config.d.ts +55 -0
  21. package/es/core/config.js +109 -0
  22. package/es/core/manifest.d.ts +15 -0
  23. package/es/core/manifest.js +43 -0
  24. package/es/core/minify.d.ts +18 -0
  25. package/es/core/minify.js +93 -0
  26. package/es/core/prepare.d.ts +12 -0
  27. package/es/core/prepare.js +86 -0
  28. package/es/core/protocol.d.ts +2 -0
  29. package/es/core/protocol.js +4 -0
  30. package/es/core/zip.d.ts +4 -0
  31. package/es/core/zip.js +17 -0
  32. package/es/dev/grading.d.ts +15 -0
  33. package/es/dev/grading.js +37 -0
  34. package/es/dev/host-page.d.ts +7 -0
  35. package/es/dev/host-page.js +240 -0
  36. package/es/dev/inject.d.ts +8 -0
  37. package/es/dev/inject.js +38 -0
  38. package/es/dev/mock-api.d.ts +65 -0
  39. package/es/dev/mock-api.js +269 -0
  40. package/es/dev/server.d.ts +24 -0
  41. package/es/dev/server.js +294 -0
  42. package/es/engines/static/index.d.ts +3 -0
  43. package/es/engines/static/index.js +11 -0
  44. package/es/engines/types.d.ts +12 -0
  45. package/es/engines/vite/index.d.ts +2 -0
  46. package/es/engines/vite/index.js +4 -0
  47. package/es/index.d.ts +2 -0
  48. package/es/index.js +2 -0
  49. package/es/rules/check.d.ts +2 -0
  50. package/es/rules/check.js +209 -0
  51. package/es/rules/index.d.ts +8 -0
  52. package/es/rules/index.js +7 -0
  53. package/es/rules/manifest.d.ts +39 -0
  54. package/es/rules/manifest.js +168 -0
  55. package/es/rules/node.d.ts +11 -0
  56. package/es/rules/node.js +87 -0
  57. package/es/rules/path.d.ts +7 -0
  58. package/es/rules/path.js +35 -0
  59. package/es/rules/refs.d.ts +19 -0
  60. package/es/rules/refs.js +111 -0
  61. package/es/rules/skip.d.ts +12 -0
  62. package/es/rules/skip.js +55 -0
  63. package/es/rules/spec.d.ts +3 -0
  64. package/es/rules/spec.js +6 -0
  65. package/es/rules/types.d.ts +138 -0
  66. package/es/rules/unused.d.ts +7 -0
  67. package/es/rules/unused.js +21 -0
  68. package/es/rules/zip.d.ts +13 -0
  69. package/es/rules/zip.js +45 -0
  70. package/es/rules.json.js +3 -0
  71. package/es/types.d.ts +4 -0
  72. package/es/version.d.ts +1 -0
  73. package/es/version.js +3 -0
  74. package/package.json +48 -3
  75. package/rules.json +555 -0
  76. package/templates/_shared/lib/cdk-mock.d.ts +94 -0
  77. package/templates/_shared/lib/cdk-mock.js +429 -0
  78. package/templates/_shared/lib/cdk.js +3 -0
  79. package/templates/_shared/lib/elice-content.css +252 -0
  80. package/templates/_shared/lib/elice-content.d.ts +121 -0
  81. package/templates/_shared/lib/elice-content.js +541 -0
  82. package/templates/_shared/lib/elice-tokens.css +446 -0
  83. package/templates/blank/README.md +64 -0
  84. package/templates/blank/content.json +4 -0
  85. package/templates/blank/edit.html +15 -0
  86. package/templates/blank/elice.config.json +12 -0
  87. package/templates/blank/gitignore +3 -0
  88. package/templates/blank/index.html +15 -0
  89. package/templates/blank/instructor.html +15 -0
  90. package/templates/blank/screens/edit.js +21 -0
  91. package/templates/blank/screens/instructor.js +9 -0
  92. package/templates/blank/screens/learn.js +19 -0
  93. package/templates/blank/styles.css +1 -0
  94. package/templates/quiz/README.md +108 -0
  95. package/templates/quiz/content.json +81 -0
  96. package/templates/quiz/core/behaviors.d.ts +59 -0
  97. package/templates/quiz/core/behaviors.js +309 -0
  98. package/templates/quiz/core/dom.d.ts +13 -0
  99. package/templates/quiz/core/dom.js +83 -0
  100. package/templates/quiz/core/editor.d.ts +48 -0
  101. package/templates/quiz/core/editor.js +206 -0
  102. package/templates/quiz/core/markdown.d.ts +2 -0
  103. package/templates/quiz/core/markdown.js +84 -0
  104. package/templates/quiz/core/model.d.ts +20 -0
  105. package/templates/quiz/core/model.js +203 -0
  106. package/templates/quiz/edit.html +17 -0
  107. package/templates/quiz/elice.config.json +14 -0
  108. package/templates/quiz/gitignore +3 -0
  109. package/templates/quiz/grading.json +13 -0
  110. package/templates/quiz/index.html +17 -0
  111. package/templates/quiz/instructor.html +17 -0
  112. package/templates/quiz/screens/edit.js +139 -0
  113. package/templates/quiz/screens/instructor.js +27 -0
  114. package/templates/quiz/screens/learn.js +50 -0
  115. package/templates/quiz/styles.css +510 -0
  116. package/templates/quiz/ui/templates/choice.js +22 -0
  117. package/templates/quiz/ui/templates/edit.d.ts +14 -0
  118. package/templates/quiz/ui/templates/edit.js +187 -0
  119. package/templates/quiz/ui/templates/group.js +47 -0
  120. package/templates/quiz/ui/templates/index.d.ts +5 -0
  121. package/templates/quiz/ui/templates/index.js +17 -0
  122. package/templates/quiz/ui/templates/order.js +35 -0
  123. package/templates/quiz/ui/templates/page.js +29 -0
  124. package/templates/quiz/ui/templates/question.js +28 -0
  125. package/templates/quiz/ui/templates/text.js +16 -0
  126. package/templates/quiz/ui/texts.d.ts +3 -0
  127. package/templates/quiz/ui/texts.js +128 -0
  128. package/templates/quiz/ui/theme.css +50 -0
@@ -0,0 +1,230 @@
1
+ import { access, readFile, appendFile } from 'node:fs/promises';
2
+ import { resolve, join } from 'node:path';
3
+ import { loadConfig, CONFIG_FILE } from '../../core/config.js';
4
+ import { prepareContent } from '../../core/prepare.js';
5
+ import { checkFiles } from '../../rules/check.js';
6
+ import { lineSkipper } from '../../rules/skip.js';
7
+ import { RULES_VERSION } from '../../rules/spec.js';
8
+ import 'fflate';
9
+ import { VERSION } from '../../version.js';
10
+
11
+ const usage = `사용법: ecdk doctor [프로젝트 폴더] [--fix] [--json]
12
+
13
+ 환경(Node, 패키지 매니저)과 프로젝트(설정, 원본, 정답 유출, 검사)를 점검한다.
14
+ --fix 자동으로 고칠 수 있는 항목(auto)을 고친다
15
+
16
+ 종료 코드: 0 실패 없음 · 1 실패 있음 · 2 잘못된 사용`;
17
+ const MIN_NODE = [20, 19];
18
+ const LOCKFILES = {
19
+ 'package-lock.json': 'npm',
20
+ 'pnpm-lock.yaml': 'pnpm',
21
+ 'yarn.lock': 'yarn',
22
+ 'bun.lockb': 'bun',
23
+ 'bun.lock': 'bun'
24
+ };
25
+ const exists = p => access(p).then(() => true, () => false);
26
+ function checkNode(version) {
27
+ const [major = 0, minor = 0] = version.replace(/^v/, '').split('.').map(Number);
28
+ const ok = major > MIN_NODE[0] || major === MIN_NODE[0] && minor >= MIN_NODE[1];
29
+ return ok ? {
30
+ id: 'env.node',
31
+ level: 'ok',
32
+ message: `Node ${version}`
33
+ } : {
34
+ id: 'env.node',
35
+ level: 'fail',
36
+ message: `Node ${version}은 지원하지 않습니다 (${MIN_NODE.join('.')} 이상 필요).`,
37
+ fix: {
38
+ description: 'Node 22 LTS 이상 설치',
39
+ command: 'https://nodejs.org',
40
+ auto: false
41
+ }
42
+ };
43
+ }
44
+ async function checkPackageManager(dir) {
45
+ const found = [];
46
+ for (const [file, pm] of Object.entries(LOCKFILES)) if (await exists(join(dir, file))) found.push(`${pm}(${file})`);
47
+ if (found.length > 1) return {
48
+ id: 'env.package-manager',
49
+ level: 'warn',
50
+ message: `잠금 파일이 여러 개입니다: ${found.join(', ')}. 설치 결과가 사람마다 달라질 수 있습니다.`,
51
+ fix: {
52
+ description: '쓰는 패키지 매니저 하나의 잠금 파일만 남기기',
53
+ auto: false
54
+ }
55
+ };
56
+ return {
57
+ id: 'env.package-manager',
58
+ level: 'ok',
59
+ message: found[0] ?? '잠금 파일 없음 (프로젝트 없이 단일 콘텐츠로 사용 중)'
60
+ };
61
+ }
62
+ async function checkGitignore(dir, config) {
63
+ const path = join(dir, '.gitignore');
64
+ const lines = (await readFile(path, 'utf8').catch(() => '')).split(/\r?\n/).map(l => l.trim());
65
+ const want = [`${config.outDir.replace(/^\.\//, '').replace(/\/$/, '')}/`, '.env'];
66
+ const missing = want.filter(w => !lines.includes(w) && !lines.includes(w.replace(/\/$/, '')) && !lines.includes(`/${w}`));
67
+ if (missing.length === 0) return {
68
+ id: 'project.gitignore',
69
+ level: 'ok',
70
+ message: '.gitignore에 산출물·.env 포함'
71
+ };
72
+ return {
73
+ id: 'project.gitignore',
74
+ level: 'warn',
75
+ message: `.gitignore에 ${missing.join(', ')}가 없습니다. 빌드 결과나 비밀 값이 저장소에 올라갈 수 있습니다.`,
76
+ fix: {
77
+ description: `.gitignore에 ${missing.join(', ')} 추가`,
78
+ auto: true
79
+ },
80
+ apply: async () => {
81
+ const current = await readFile(path, 'utf8').catch(() => '');
82
+ await appendFile(path, `${current && !current.endsWith('\n') ? '\n' : ''}${missing.join('\n')}\n`);
83
+ }
84
+ };
85
+ }
86
+ async function doctor(target, opts) {
87
+ const dir = resolve(target);
88
+ const checks = [checkNode(opts.nodeVersion ?? process.version), await checkPackageManager(dir)];
89
+ let config = null;
90
+ try {
91
+ config = await loadConfig(dir);
92
+ checks.push({
93
+ id: 'project.config',
94
+ level: 'ok',
95
+ message: (await exists(join(dir, CONFIG_FILE))) ? `${CONFIG_FILE} 읽음` : `${CONFIG_FILE} 없음 (기본값 사용)`
96
+ });
97
+ } catch (e) {
98
+ checks.push({
99
+ id: 'project.config',
100
+ level: 'fail',
101
+ message: `${CONFIG_FILE}을 읽을 수 없습니다: ${e.message}`
102
+ });
103
+ }
104
+ if (config) {
105
+ const srcDir = resolve(dir, config.root);
106
+ if (!(await exists(srcDir))) {
107
+ checks.push({
108
+ id: 'project.root',
109
+ level: 'fail',
110
+ message: `원본 폴더가 없습니다: ${config.root}`
111
+ });
112
+ } else {
113
+ let prepared = null;
114
+ try {
115
+ prepared = await prepareContent(dir, config);
116
+ } catch (e) {
117
+ checks.push({
118
+ id: 'project.root',
119
+ level: 'fail',
120
+ message: e.message
121
+ });
122
+ }
123
+ if (prepared) {
124
+ const {
125
+ files
126
+ } = prepared;
127
+ checks.push({
128
+ id: 'project.root',
129
+ level: 'ok',
130
+ message: `원본 ${config.root} · zip에 들어갈 파일 ${files.length}개`
131
+ });
132
+ // 빌드에서 빠지는 정답·설정 파일을 콘텐츠가 참조하면: 배포본에서 깨지고, 정답을 콘텐츠로 가져오려 한 신호.
133
+ // 주석 줄은 보지 않고, 일부러 참조하는 줄은 `ecdk-ignore project.answer-import`로 끈다
134
+ // (템플릿 mock SDK는 프로젝트 폴더에서 열 때 로컬 채점용으로 elice.config.json · grading.json을 읽는다)
135
+ const decoder = new TextDecoder();
136
+ const leaks = files.filter(f => /\.(html?|m?js|css)$/i.test(f.path)).filter(f => referencesAnswerFile(decoder.decode(f.data))).map(f => f.path);
137
+ checks.push(leaks.length > 0 ? {
138
+ id: 'project.answer-import',
139
+ level: 'fail',
140
+ message: `콘텐츠가 정답·설정 파일을 참조합니다: ${leaks.join(', ')}. 정답은 서버에서 채점하고 콘텐츠에는 넣지 않습니다.`,
141
+ fix: {
142
+ description: '정답은 편집 화면의 채점 설정으로 따로 올리고, 콘텐츠는 답만 제출',
143
+ auto: false
144
+ }
145
+ } : {
146
+ id: 'project.answer-import',
147
+ level: 'ok',
148
+ message: '콘텐츠가 정답·설정 파일을 참조하지 않음'
149
+ });
150
+ const result = checkFiles(files, {
151
+ input: 'zip'
152
+ });
153
+ const errors = result.issues.filter(i => i.level === 'error');
154
+ const warns = result.issues.length - errors.length;
155
+ checks.push(errors.length > 0 ? {
156
+ id: 'project.check',
157
+ level: 'fail',
158
+ message: `검사 오류 ${errors.length}개 · 경고 ${warns}개 (${[...new Set(errors.map(i => i.id))].join(', ')})`,
159
+ fix: {
160
+ description: '자세한 위치 확인',
161
+ command: 'ecdk build',
162
+ auto: false
163
+ }
164
+ } : {
165
+ id: 'project.check',
166
+ level: warns > 0 ? 'warn' : 'ok',
167
+ message: `검사 오류 0개 · 경고 ${warns}개`
168
+ });
169
+ const near = result.issues.filter(i => i.id === 'limit.near');
170
+ if (near.length > 0) checks.push({
171
+ id: 'project.limits',
172
+ level: 'warn',
173
+ message: near.map(i => i.message).join(' ')
174
+ });
175
+ }
176
+ }
177
+ if (await exists(join(dir, 'package.json'))) checks.push(await checkGitignore(dir, config));
178
+ }
179
+ // 서버 API(D8)가 정해지면 규칙·프로토콜 버전을 서버와 비교
180
+ checks.push({
181
+ id: 'compat.server',
182
+ level: 'skip',
183
+ message: `서버 규칙 버전 비교는 아직 없음 (로컬 규칙 ${RULES_VERSION})`
184
+ });
185
+ if (opts.fix) {
186
+ for (const c of checks) {
187
+ if (c.apply && c.level !== 'ok') {
188
+ await c.apply();
189
+ c.fixed = true;
190
+ }
191
+ }
192
+ }
193
+ const out = checks.map(({
194
+ apply,
195
+ ...c
196
+ }) => c);
197
+ return {
198
+ ok: !out.some(c => c.level === 'fail'),
199
+ cli: VERSION,
200
+ rules: RULES_VERSION,
201
+ checks: out
202
+ };
203
+ }
204
+ function formatText(r) {
205
+ const lines = r.checks.map(c => {
206
+ const head = `[${c.fixed ? 'fixed' : c.level}] ${c.id.padEnd(22)} ${c.message}`;
207
+ if (!c.fix || c.fixed || c.level === 'ok') return head;
208
+ return `${head}\n${' '.repeat(8)}→ ${c.fix.description}${c.fix.command ? `: ${c.fix.command}` : ''}${c.fix.auto ? ' (--fix로 자동)' : ''}`;
209
+ });
210
+ const count = l => r.checks.filter(c => c.level === l && !c.fixed).length;
211
+ lines.push('', `결과: 실패 ${count('fail')} · 경고 ${count('warn')} (ecdk ${r.cli}, 규칙 ${r.rules}, 기계용: --json)`);
212
+ return lines.join('\n');
213
+ }
214
+ async function run(args) {
215
+ const result = await doctor(args.target, {
216
+ fix: args.fix
217
+ });
218
+ return {
219
+ exitCode: result.ok ? 0 : 1,
220
+ output: args.json ? JSON.stringify(result, null, 2) : formatText(result)
221
+ };
222
+ }
223
+ const ANSWER_FILE = /\b(?:answers\.[a-z]+|elice\.config\.[a-z]+|grading\.json)\b/i;
224
+ /** 주석뿐이 아닌 줄에서 정답·설정 파일 이름이 나오는지. 줄 건너뛰기는 금지 API 검사와 같은 규칙(content-rules lineSkipper) */
225
+ function referencesAnswerFile(text) {
226
+ const skip = lineSkipper(text);
227
+ return skip.lines.some((line, i) => ANSWER_FILE.test(line) && !skip.isSkipped(i + 1, 'project.answer-import'));
228
+ }
229
+
230
+ export { checkNode, doctor, formatText, referencesAnswerFile, run, usage };
@@ -0,0 +1,21 @@
1
+ export interface SourceFile {
2
+ path: string;
3
+ data: Uint8Array;
4
+ }
5
+ export interface Excluded {
6
+ path: string;
7
+ /** link: 심볼릭 링크 등 일반 파일 · 폴더가 아닌 항목 (따라가지 않고 빼되 보고는 한다) */
8
+ reason: 'secret' | 'dev' | 'junk' | 'project' | 'config' | 'link';
9
+ }
10
+ /**
11
+ * 원본 폴더에서 콘텐츠 파일만 모은다. 정답·비밀·개발용·OS 파일, 프로젝트 파일, 산출물 폴더, 설정의 exclude를 뺀다.
12
+ * 빠진 목록은 보고서에 남긴다 (조용히 빼지 않음).
13
+ */
14
+ export declare function collectSources(srcDir: string, opts: {
15
+ skipDirs: string[];
16
+ exclude: string[];
17
+ projectRoot: boolean;
18
+ }): Promise<{
19
+ files: SourceFile[];
20
+ excluded: Excluded[];
21
+ }>;
@@ -0,0 +1,89 @@
1
+ import { readdir, readFile } from 'node:fs/promises';
2
+ import { join, relative, sep } from 'node:path';
3
+ import 'fflate';
4
+ import { globToRegExp } from '../rules/path.js';
5
+ import { rules } from '../rules/spec.js';
6
+
7
+ /** 콘텐츠가 아니라 프로젝트 도구가 쓰는 파일. 원본 폴더가 프로젝트 루트일 때 빠진다. */
8
+ const PROJECT_FILES = ['package.json', 'package-lock.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'yarn.lock', 'bun.lockb', 'tsconfig*.json', '*.d.ts',
9
+ // 편집기 자동완성용 타입 (템플릿 lib/elice-content.d.ts)
10
+ 'README*', 'LICENSE*', '.*'];
11
+ function matcher(patterns) {
12
+ const names = patterns.filter(p => !p.includes('/')).map(globToRegExp);
13
+ const prefixes = patterns.filter(p => p.includes('/')).map(p => p.replace(/^\.\//, '').replace(/\/$/, ''));
14
+ return path => {
15
+ const name = path.slice(path.lastIndexOf('/') + 1);
16
+ return names.some(re => re.test(name)) || prefixes.some(pre => path === pre || path.startsWith(`${pre}/`));
17
+ };
18
+ }
19
+ /**
20
+ * 원본 폴더에서 콘텐츠 파일만 모은다. 정답·비밀·개발용·OS 파일, 프로젝트 파일, 산출물 폴더, 설정의 exclude를 뺀다.
21
+ * 빠진 목록은 보고서에 남긴다 (조용히 빼지 않음).
22
+ */
23
+ async function collectSources(srcDir, opts) {
24
+ const {
25
+ secret,
26
+ dev,
27
+ junk
28
+ } = rules.excluded;
29
+ const groups = [['secret', matcher(secret.files), new Set(secret.dirs)], ['dev', matcher(dev.files), new Set(dev.dirs)], ['junk', matcher(junk.files), new Set(junk.dirs)]];
30
+ const isProject = matcher(opts.projectRoot ? PROJECT_FILES : []);
31
+ const isConfigExcluded = matcher(opts.exclude);
32
+ const skip = new Set(opts.skipDirs.map(d => d.replace(/\/$/, '')));
33
+ const files = [];
34
+ const excluded = [];
35
+ async function walk(dir) {
36
+ const entries = await readdir(dir, {
37
+ withFileTypes: true
38
+ });
39
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
40
+ for (const e of entries) {
41
+ const abs = join(dir, e.name);
42
+ const rel = relative(srcDir, abs).split(sep).join('/');
43
+ if (e.isDirectory()) {
44
+ if (skip.has(rel)) continue;
45
+ const group = groups.find(([,, dirs]) => dirs.has(e.name));
46
+ if (group) excluded.push({
47
+ path: `${rel}/`,
48
+ reason: group[0]
49
+ });else if (isConfigExcluded(rel)) excluded.push({
50
+ path: `${rel}/`,
51
+ reason: 'config'
52
+ });else if (opts.projectRoot && e.name.startsWith('.')) excluded.push({
53
+ path: `${rel}/`,
54
+ reason: 'project'
55
+ });else await walk(abs);
56
+ continue;
57
+ }
58
+ if (!e.isFile()) {
59
+ // 링크로 연결한 이미지 폴더 등이 조용히 빠지면 ref.missing만 보게 된다: 원인을 남긴다
60
+ excluded.push({
61
+ path: rel,
62
+ reason: 'link'
63
+ });
64
+ continue;
65
+ }
66
+ const group = groups.find(([, match]) => match(rel));
67
+ if (group) excluded.push({
68
+ path: rel,
69
+ reason: group[0]
70
+ });else if (isProject(rel)) excluded.push({
71
+ path: rel,
72
+ reason: 'project'
73
+ });else if (isConfigExcluded(rel)) excluded.push({
74
+ path: rel,
75
+ reason: 'config'
76
+ });else files.push({
77
+ path: rel,
78
+ data: new Uint8Array(await readFile(abs))
79
+ });
80
+ }
81
+ }
82
+ await walk(srcDir);
83
+ return {
84
+ files,
85
+ excluded
86
+ };
87
+ }
88
+
89
+ export { collectSources };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * 채점 유형. 원본은 rules.json `manifest.gradingTypes`이고, 타입 검사(오타 · 막아 둔 manual)를 위해 여기 리터럴로 둔다.
3
+ * 둘이 같은지는 docs.test.ts가 대조한다. 수동 채점 manual · 채점 없음 none은 Custom HTML에서 쓰지 않음
4
+ */
5
+ export declare const GRADING_TYPES: readonly ["on_access", "on_submit", "pattern", "rubric"];
6
+ export type GradingType = (typeof GRADING_TYPES)[number];
7
+ /**
8
+ * 로컬 채점 설정(유형 · 정답 · 채점 기준). 프로젝트 맨 위 `grading.json`에 적는다. LXP 채점 설정에서 교육자가 고르고
9
+ * 넣는 값과 같다. zip에는 들어가지 않는다 (운영은 LXP 채점 설정). CLI · mock의 로컬 채점에만 쓴다.
10
+ */
11
+ export interface GradingData {
12
+ /** 로컬에서 흉내 낼 유형 (gradingTypes 중 하나). 없으면 gradingTypes의 첫 유형 */
13
+ type?: GradingType;
14
+ match?: 'exact' | 'regex';
15
+ answer_key?: unknown;
16
+ rubric?: string;
17
+ }
18
+ /** 로컬 채점에 쓰는 값: grading.json에 유형을 채운 것. elice-material `material_version.grading`과 같은 모양 */
19
+ export interface GradingConfig extends GradingData {
20
+ type: GradingType;
21
+ }
22
+ export declare const GRADING_DATA_FILE = "grading.json";
23
+ export interface ContentConfig {
24
+ /** 콘텐츠 원본 폴더 (프로젝트 기준). 기본 '.' */
25
+ root: string;
26
+ /** 산출물 폴더. 기본 'dist' */
27
+ outDir: string;
28
+ /** 추가로 뺄 파일·폴더 (basename glob `*` 또는 프로젝트 기준 경로 접두사) */
29
+ exclude: string[];
30
+ /** 용도 → metadata.json `kind`. material: 자료 본문(기본) · description: 다른 자료(실습 등)의 문제 설명 */
31
+ kind?: 'material' | 'description';
32
+ /** 화면별 진입 파일 → build가 metadata.json로 만든다. 없으면 원본의 metadata.json, 그것도 없으면 { learn: 'index.html' } */
33
+ screens?: Record<string, string>;
34
+ /** 이 자료가 지원하는 채점 유형 → metadata.json `gradingTypes` (자료 본문은 필수). 로컬 채점 유형 · 정답은 grading.json */
35
+ gradingTypes?: GradingType[];
36
+ /** true면 build가 JS · CSS · JSON을 줄여 zip에 넣는다 (용량 줄이기). 기본 false */
37
+ minify?: boolean;
38
+ /**
39
+ * 학습 참고 내용 파일 이름 (원본 최상위 .txt). 기본 rules.json `manifest.commentaryFile`(commentary.txt)이 있으면 그것.
40
+ * zip에 그대로 들어가고 build가 metadata.json `commentary`에 이름을 적는다
41
+ */
42
+ commentary?: string;
43
+ /** minify와 함께: 줄인 JS · CSS마다 .map을 zip에 넣어 운영에서도 원본 위치로 오류를 본다 (용량이 늘어남) */
44
+ sourcemap?: boolean;
45
+ /** ecdk create가 적는 템플릿과 버전 (예: "quiz@0.1.0"). metadata.json build.template으로 */
46
+ template?: string;
47
+ }
48
+ export declare const CONFIG_FILE = "elice.config.json";
49
+ /** 1단계는 JSON만. `.ts` 설정은 Node 20의 TS 실행 지원 문제로 엔진 작업(3단계)과 함께 결정. */
50
+ export declare function loadConfig(projectDir: string): Promise<ContentConfig>;
51
+ /**
52
+ * 로컬 채점용 설정: grading.json(있으면) + 유형. 유형은 grading.json `type`, 없으면 gradingTypes의 첫 유형.
53
+ * 지원 유형이 없으면(문제 설명) undefined.
54
+ */
55
+ export declare function loadGrading(projectDir: string, config: ContentConfig): Promise<GradingConfig | undefined>;
@@ -0,0 +1,109 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import 'fflate';
4
+ import { gradingTypesError } from '../rules/manifest.js';
5
+ import { rules } from '../rules/spec.js';
6
+
7
+ /**
8
+ * 채점 유형. 원본은 rules.json `manifest.gradingTypes`이고, 타입 검사(오타 · 막아 둔 manual)를 위해 여기 리터럴로 둔다.
9
+ * 둘이 같은지는 docs.test.ts가 대조한다. 수동 채점 manual · 채점 없음 none은 Custom HTML에서 쓰지 않음
10
+ */
11
+ const GRADING_TYPES = ['on_access', 'on_submit', 'pattern', 'rubric'];
12
+ const GRADING_DATA_FILE = 'grading.json';
13
+ const GRADING_DATA_KEYS = ['type', 'match', 'answer_key', 'rubric'];
14
+ const CONFIG_FILE = 'elice.config.json';
15
+ /** JSON 형식 오류에 파일 이름을 붙인다 (SyntaxError만 나오면 어느 파일인지 모름) */
16
+ function parseJson(raw, fail) {
17
+ try {
18
+ return JSON.parse(raw);
19
+ } catch (e) {
20
+ throw fail(`JSON 형식이 아닙니다 (${e.message}).`);
21
+ }
22
+ }
23
+ const defaults = {
24
+ root: '.',
25
+ outDir: 'dist',
26
+ exclude: []
27
+ };
28
+ const isStringRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v) && Object.values(v).every(x => typeof x === 'string');
29
+ /** 1단계는 JSON만. `.ts` 설정은 Node 20의 TS 실행 지원 문제로 엔진 작업(3단계)과 함께 결정. */
30
+ async function loadConfig(projectDir) {
31
+ let raw;
32
+ try {
33
+ raw = await readFile(join(projectDir, CONFIG_FILE), 'utf8');
34
+ } catch (e) {
35
+ if (e.code === 'ENOENT') return {
36
+ ...defaults
37
+ };
38
+ throw e;
39
+ }
40
+ const fail = msg => new Error(`${CONFIG_FILE}: ${msg}`);
41
+ const json = parseJson(raw, fail);
42
+ for (const key of ['root', 'outDir']) {
43
+ if (json[key] !== undefined && typeof json[key] !== 'string') throw fail(`${key}는 문자열이어야 합니다.`);
44
+ }
45
+ if (json.exclude !== undefined && !(Array.isArray(json.exclude) && json.exclude.every(x => typeof x === 'string'))) throw fail('exclude는 문자열 배열이어야 합니다.');
46
+ // metadata.json의 screens({ learn: { enabled, entry } })와 달리 켤 화면만 파일 이름으로 적는다 (ADR 0004)
47
+ if (json.screens !== undefined && !isStringRecord(json.screens)) throw fail('screens는 켤 화면만 파일 이름으로 적습니다: { "learn": "index.html", "instructor": "..." } (metadata.json의 { "enabled", "entry" } 모양과 다름).');
48
+ // 오타는 metadata.json 파서와 같은 문구로 막는다 (조용히 빠지면 그 화면이 꺼진 채로 만들어짐)
49
+ const unknownScreen = Object.keys(json.screens ?? {}).find(m => !rules.manifest.modes.includes(m));
50
+ if (unknownScreen) throw fail(`알 수 없는 화면입니다: ${unknownScreen} (가능: ${rules.manifest.modes.join(', ')})`);
51
+ if (json.minify !== undefined && typeof json.minify !== 'boolean') throw fail('minify는 true 또는 false여야 합니다.');
52
+ if (json.sourcemap !== undefined && typeof json.sourcemap !== 'boolean') throw fail('sourcemap은 true 또는 false여야 합니다.');
53
+ if (json.sourcemap && !json.minify) throw fail('sourcemap은 minify와 함께 씁니다 ("minify": true). 줄이지 않으면 원본 그대로라 필요 없습니다.');
54
+ if (json.template !== undefined && typeof json.template !== 'string') throw fail('template은 문자열이어야 합니다 (ecdk create가 적는 값).');
55
+ if (json.answers !== undefined) throw fail('answers 대신 gradingTypes와 grading.json을 써 주세요 (예: elice.config.json { "gradingTypes": ["pattern"] }, grading.json { "type": "pattern", "match": "exact", "answer_key": ... }).');
56
+ const legacy = json;
57
+ if (legacy.grading !== undefined) throw fail(`grading 대신 gradingTypes에 이 자료가 지원하는 채점 유형을 모두 적어 주세요 (예: "gradingTypes": ["on_submit", "pattern"]). 로컬에서 흉내 낼 유형과 정답은 ${GRADING_DATA_FILE}에.`);
58
+ if (json.gradingTypes !== undefined) {
59
+ const error = gradingTypesError(json.gradingTypes, GRADING_TYPES);
60
+ if (error) throw fail(error);
61
+ }
62
+ if (json.commentary !== undefined && typeof json.commentary !== 'string') throw fail('commentary는 학습 참고 내용 파일 이름(문자열)이어야 합니다. 예: "commentary.txt"');
63
+ if (json.kind !== undefined && json.kind !== 'material' && json.kind !== 'description') throw fail('kind는 material(자료 본문) 또는 description(문제 설명)이어야 합니다.');
64
+ // 용도별로 켤 수 있는 화면은 rules.json manifest.kindModes (문제 설명은 학생 화면만)
65
+ if (json.kind && json.screens) {
66
+ const allowed = rules.manifest.kindModes[json.kind] ?? rules.manifest.modes;
67
+ const extra = Object.keys(json.screens).filter(m => !allowed.includes(m));
68
+ if (extra.length > 0) throw fail(`${json.kind === 'description' ? '문제 설명(kind: description)' : json.kind}은 ${allowed.join(' · ')} 화면만 켤 수 있습니다. screens에서 ${extra.join(', ')}를 지워 주세요.`);
69
+ }
70
+ // 문제 설명은 채점하지 않는다: 채점은 설명을 붙인 문제 자료가 한다
71
+ if (json.kind === 'description' && json.gradingTypes !== undefined) throw fail('문제 설명(kind: description)은 채점하지 않습니다. gradingTypes를 지워 주세요 (채점은 문제 자료의 채점 설정에서).');
72
+ return {
73
+ ...defaults,
74
+ ...json
75
+ };
76
+ }
77
+ /**
78
+ * 로컬 채점용 설정: grading.json(있으면) + 유형. 유형은 grading.json `type`, 없으면 gradingTypes의 첫 유형.
79
+ * 지원 유형이 없으면(문제 설명) undefined.
80
+ */
81
+ async function loadGrading(projectDir, config) {
82
+ const supported = config.gradingTypes;
83
+ if (!supported || supported.length === 0) return undefined;
84
+ let raw;
85
+ try {
86
+ raw = await readFile(join(projectDir, GRADING_DATA_FILE), 'utf8');
87
+ } catch (e) {
88
+ if (e.code === 'ENOENT') return {
89
+ type: supported[0]
90
+ };
91
+ throw e;
92
+ }
93
+ const fail = msg => new Error(`${GRADING_DATA_FILE}: ${msg}`);
94
+ const data = parseJson(raw, fail);
95
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) throw fail('객체여야 합니다. 예: { "type": "pattern", "match": "exact", "answer_key": { "answers": { "q1": "b" } } }');
96
+ const unknown = Object.keys(data).filter(k => !GRADING_DATA_KEYS.includes(k));
97
+ if (unknown.length > 0) throw fail(`알 수 없는 필드입니다: ${unknown.join(', ')} (가능: ${GRADING_DATA_KEYS.join(', ')})`);
98
+ const {
99
+ type,
100
+ ...rest
101
+ } = data;
102
+ if (type !== undefined && !supported.includes(type)) throw fail(`type은 elice.config.json gradingTypes(${supported.join(', ')}) 중 하나여야 합니다: ${type}`);
103
+ return {
104
+ ...rest,
105
+ type: type ?? supported[0]
106
+ };
107
+ }
108
+
109
+ export { CONFIG_FILE, GRADING_DATA_FILE, GRADING_TYPES, loadConfig, loadGrading };
@@ -0,0 +1,15 @@
1
+ import { type BuildInfo } from '../rules/index.js';
2
+ import type { SourceFile } from './collect.js';
3
+ /**
4
+ * metadata.json의 build. 같은 입력이면 같은 결과가 나오도록 시각 등 바뀌는 값은 넣지 않는다.
5
+ * template은 ecdk create가 elice.config.json에 적은 값, sdk는 묶어 넣은 SDK 파일 머리말에서 읽는다.
6
+ */
7
+ export declare function createBuildInfo(engine: string, extra?: {
8
+ template?: string | undefined;
9
+ files?: SourceFile[];
10
+ }): BuildInfo;
11
+ /**
12
+ * zip 내용의 지문. metadata.json을 뺀 파일을 이름순으로 `경로 \0 길이 \0 내용`을 이어 SHA-256.
13
+ * 서버나 누구든 zip을 풀어 같은 방법으로 계산하면 빌드 뒤 바뀌었는지 알 수 있다.
14
+ */
15
+ export declare function contentDigest(files: SourceFile[], skip?: string): string;
@@ -0,0 +1,43 @@
1
+ import { createHash } from 'node:crypto';
2
+ import 'fflate';
3
+ import { RULES_VERSION } from '../rules/spec.js';
4
+ import { VERSION } from '../version.js';
5
+ import { PROTOCOL_VERSION } from './protocol.js';
6
+
7
+ /** lib/cdk.js 머리말: `/* @eliceio/cdk 1.0.0 — UMD. …` 또는 `/* @eliceio/cdk 1.0.0 (브랜치@커밋) · …` */
8
+ const SDK_HEADER = /^\/\* @eliceio\/cdk (\S+)(?: \(([^)]+)\))?/;
9
+ /**
10
+ * metadata.json의 build. 같은 입력이면 같은 결과가 나오도록 시각 등 바뀌는 값은 넣지 않는다.
11
+ * template은 ecdk create가 elice.config.json에 적은 값, sdk는 묶어 넣은 SDK 파일 머리말에서 읽는다.
12
+ */
13
+ function createBuildInfo(engine, extra = {}) {
14
+ const sdkFile = extra.files?.find(f => f.path === 'lib/cdk.js');
15
+ const header = sdkFile ? SDK_HEADER.exec(new TextDecoder().decode(sdkFile.data.subarray(0, 300))) : null;
16
+ return {
17
+ cli: VERSION,
18
+ rules: RULES_VERSION,
19
+ protocol: PROTOCOL_VERSION,
20
+ engine,
21
+ ...(extra.template ? {
22
+ template: extra.template
23
+ } : {}),
24
+ ...(header ? {
25
+ sdk: header[2] ? `${header[1]} (${header[2]})` : header[1]
26
+ } : {})
27
+ };
28
+ }
29
+ /**
30
+ * zip 내용의 지문. metadata.json을 뺀 파일을 이름순으로 `경로 \0 길이 \0 내용`을 이어 SHA-256.
31
+ * 서버나 누구든 zip을 풀어 같은 방법으로 계산하면 빌드 뒤 바뀌었는지 알 수 있다.
32
+ */
33
+ function contentDigest(files, skip = 'metadata.json') {
34
+ const hash = createHash('sha256');
35
+ for (const f of [...files].sort((a, b) => a.path < b.path ? -1 : 1)) {
36
+ if (f.path === skip) continue;
37
+ hash.update(`${f.path}\0${f.data.byteLength}\0`);
38
+ hash.update(f.data);
39
+ }
40
+ return `sha256-${hash.digest('base64')}`;
41
+ }
42
+
43
+ export { contentDigest, createBuildInfo };
@@ -0,0 +1,18 @@
1
+ import type { SourceFile } from './collect.js';
2
+ export interface MinifyReport {
3
+ /** 줄인 파일 수 */
4
+ files: number;
5
+ before: number;
6
+ after: number;
7
+ /** 만든 .map 수와 크기 (sourcemap일 때) */
8
+ maps?: {
9
+ files: number;
10
+ bytes: number;
11
+ } | undefined;
12
+ }
13
+ export declare function minifyFiles(files: SourceFile[], { sourcemap }?: {
14
+ sourcemap?: boolean | undefined;
15
+ }): Promise<{
16
+ files: SourceFile[];
17
+ report: MinifyReport;
18
+ }>;