@eliceio/cdk-cli 0.1.0-alpha.3 → 0.1.0-alpha.4

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 (82) hide show
  1. package/README.md +196 -144
  2. package/es/cli.js +6 -1
  3. package/es/commands/build/index.d.ts +1 -1
  4. package/es/commands/build/index.js +11 -12
  5. package/es/commands/check/index.d.ts +5 -2
  6. package/es/commands/check/index.js +15 -9
  7. package/es/commands/create/index.d.ts +4 -0
  8. package/es/commands/create/index.js +30 -7
  9. package/es/commands/create/install.d.ts +17 -0
  10. package/es/commands/create/install.js +53 -0
  11. package/es/commands/create/scaffold.d.ts +4 -1
  12. package/es/commands/create/scaffold.js +19 -13
  13. package/es/commands/dev/index.d.ts +1 -1
  14. package/es/commands/dev/index.js +4 -4
  15. package/es/commands/doctor/index.d.ts +11 -1
  16. package/es/commands/doctor/index.js +124 -36
  17. package/es/core/collect.d.ts +5 -2
  18. package/es/core/config.d.ts +95 -29
  19. package/es/core/config.js +253 -47
  20. package/es/core/manifest.d.ts +2 -1
  21. package/es/core/manifest.js +2 -1
  22. package/es/core/minify.js +2 -2
  23. package/es/core/prepare.d.ts +18 -2
  24. package/es/core/prepare.js +46 -15
  25. package/es/core/project-check.d.ts +18 -7
  26. package/es/core/project-check.js +35 -8
  27. package/es/core/sandbox.js +2 -2
  28. package/es/core/sdk.d.ts +39 -0
  29. package/es/core/sdk.js +95 -0
  30. package/es/core/templates.d.ts +3 -3
  31. package/es/core/templates.js +4 -4
  32. package/es/dev/grading.d.ts +1 -1
  33. package/es/dev/grading.js +1 -1
  34. package/es/dev/host-page.js +2 -2
  35. package/es/dev/mock-api.d.ts +7 -8
  36. package/es/dev/mock-api.js +18 -13
  37. package/es/dev/server.js +62 -43
  38. package/es/rules/check.js +45 -9
  39. package/es/rules/manifest.d.ts +1 -1
  40. package/es/rules/manifest.js +1 -1
  41. package/es/rules/types.d.ts +18 -8
  42. package/es/rules.json.js +2 -2
  43. package/es/test-packages.d.ts +7 -0
  44. package/guides/content-development.md +63 -55
  45. package/package.json +2 -2
  46. package/rules.json +18 -3
  47. package/skills/_shared/always.md +2 -2
  48. package/skills/elice-content-check/SKILL.md +3 -1
  49. package/skills/elice-content-create/SKILL.md +5 -4
  50. package/skills/elice-content-migrate/SKILL.md +2 -2
  51. package/skills/elice-content-publish/SKILL.md +4 -3
  52. package/templates/_shared/lib/cdk-mock.js +17 -17
  53. package/templates/_shared/lib/elice-content.css +8 -0
  54. package/templates/_shared/lib/elice-content.d.ts +5 -1
  55. package/templates/_shared/lib/elice-content.js +20 -12
  56. package/templates/blank/README.md +11 -8
  57. package/templates/blank/metadata.json +11 -0
  58. package/templates/blank/package.json +13 -0
  59. package/templates/blank/screens/completion.js +2 -2
  60. package/templates/blank/screens/instructor.js +12 -5
  61. package/templates/blank/screens/learn.js +16 -11
  62. package/templates/quiz/README.md +14 -11
  63. package/templates/quiz/core/editor.d.ts +12 -1
  64. package/templates/quiz/core/editor.js +28 -5
  65. package/templates/quiz/core/model.d.ts +14 -0
  66. package/templates/quiz/core/model.js +73 -1
  67. package/templates/quiz/metadata.json +11 -0
  68. package/templates/quiz/package.json +13 -0
  69. package/templates/quiz/screens/edit.js +85 -29
  70. package/templates/quiz/screens/instructor.js +18 -12
  71. package/templates/quiz/screens/learn.js +42 -36
  72. package/templates/quiz/styles.css +47 -0
  73. package/templates/quiz/template.json +2 -2
  74. package/templates/quiz/ui/templates/edit.d.ts +1 -0
  75. package/templates/quiz/ui/templates/edit.js +37 -5
  76. package/templates/quiz/ui/texts.js +9 -7
  77. package/templates/_shared/lib/cdk.js +0 -3
  78. package/templates/blank/content.json +0 -4
  79. package/templates/blank/elice.config.json +0 -10
  80. package/templates/quiz/content.json +0 -35
  81. package/templates/quiz/elice.config.json +0 -9
  82. package/templates/quiz/grading.json +0 -4
package/es/core/config.js CHANGED
@@ -1,7 +1,7 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { readFile, writeFile, unlink } from 'node:fs/promises';
2
+ import { join, resolve, basename } from 'node:path';
3
3
  import 'fflate';
4
- import { parseCompletionPolicies, completionPolicyError, graderTypeError, COMPLETION_POLICIES_EXAMPLE } from '../rules/manifest.js';
4
+ import { completionPolicyError, parseCompletionPolicies, parseManifest, serializeManifest, graderTypeError, COMPLETION_POLICIES_EXAMPLE } from '../rules/manifest.js';
5
5
  import { rules } from '../rules/spec.js';
6
6
 
7
7
  /**
@@ -16,7 +16,11 @@ const COMPLETION_POLICIES = ['on_access', 'on_submit', 'on_graded'];
16
16
  * pattern: 정답 정규식 · rubric: AI 평가 기준. code_exec는 이번 범위 밖
17
17
  */
18
18
  const GRADER_TYPES = ['pattern', 'rubric'];
19
- const GRADING_DATA_FILE = 'grading.json';
19
+ /**
20
+ * 로컬 settings (dev 전용): `ecdk dev` 편집 화면의 saveSettings(PATCH settings)를 흉내 서버가 통째로(내용 + grading) 여기에 쓴다.
21
+ * 운영은 서버 material_version.settings. 프로젝트의 점(.) 폴더라 zip에 들어가지 않는다. build · check는 읽지 않는다
22
+ */
23
+ const SETTINGS_DATA_FILE = '.ecdk/settings.json';
20
24
  /**
21
25
  * 로컬 완료 정책 (dev 전용): `ecdk dev` 완료 정책 화면의 saveCompletionPolicy를 흉내 서버가 여기에 쓴다.
22
26
  * 운영은 서버 material_version.completion_policy. 프로젝트의 점(.) 폴더라 zip에 들어가지 않는다
@@ -26,7 +30,7 @@ const GRADING_DATA_KEYS = ['type', 'answer_key', 'rubric'];
26
30
  /** completionPolicies가 없을 때(검사 오류) ecdk dev가 흉내 내는 정책 (제출하면 완료) */
27
31
  const DEFAULT_COMPLETION_POLICY = 'on_submit';
28
32
  /**
29
- * 채점 설정 값 검사 (grading.json · 편집 화면이 저장한 settings.grading). 문제가 있으면 문장, 없으면 GradingConfig.
33
+ * 채점 설정 값 검사 (편집 화면이 저장한 settings.grading). 문제가 있으면 문장, 없으면 GradingConfig.
30
34
  * 옛 모양(`type: on_access · on_submit`, `completion_policy` · `grader_type`, `match` · 객체 정답)은 바꾸는 법을 알려 준다.
31
35
  */
32
36
  function parseGrading(data) {
@@ -64,7 +68,15 @@ function parseGrading(data) {
64
68
  rubric
65
69
  };
66
70
  }
71
+ /** 옛 설정 파일 (ADR 0011에서 없앰). 있으면 경고하고 `ecdk doctor --fix`가 옮긴다. zip에는 들어가지 않는다 */
67
72
  const CONFIG_FILE = 'elice.config.json';
73
+ const PACKAGE_FILE = 'package.json';
74
+ /** package.json에서 ecdk 빌드 옵션을 담는 키 */
75
+ const PACKAGE_CONFIG_KEY = 'ecdk';
76
+ /** package.json "ecdk"에 적을 수 있는 키 */
77
+ const BUILD_OPTION_KEYS = ['template', 'root', 'outDir', 'exclude', 'minify', 'sourcemap'];
78
+ /** metadata.json에 적는 플랫폼 필드 (package.json "ecdk" · 옛 elice.config.json에 있으면 옮기라고 알림) */
79
+ const PLATFORM_KEYS = ['kind', 'screens', 'completionPolicies', 'commentary'];
68
80
  /** JSON 형식 오류에 파일 이름을 붙인다 (SyntaxError만 나오면 어느 파일인지 모름) */
69
81
  function parseJson(raw, fail) {
70
82
  try {
@@ -78,61 +90,236 @@ const defaults = {
78
90
  outDir: 'dist',
79
91
  exclude: []
80
92
  };
81
- const isStringRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v) && Object.values(v).every(x => typeof x === 'string');
82
- /** 1단계는 JSON만. `.ts` 설정은 Node 20의 TS 실행 지원 문제로 엔진 작업(3단계)과 함께 결정. */
83
- async function loadConfig(projectDir) {
84
- let raw;
93
+ const isRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v);
94
+ const isStringRecord = v => isRecord(v) && Object.values(v).every(x => typeof x === 'string');
95
+ async function readOptional(path) {
85
96
  try {
86
- raw = await readFile(join(projectDir, CONFIG_FILE), 'utf8');
97
+ return await readFile(path, 'utf8');
87
98
  } catch (e) {
88
- if (e.code === 'ENOENT') return {
89
- ...defaults
90
- };
99
+ if (e.code === 'ENOENT') return null;
91
100
  throw e;
92
101
  }
93
- const fail = msg => new Error(`${CONFIG_FILE}: ${msg}`);
94
- const json = parseJson(raw, fail);
102
+ }
103
+ /** 정답 · 옛 completion은 어느 설정 파일에서든 같은 문구로 막는다 */
104
+ function rejectAnswersAndOldFields(json, fail) {
105
+ if (json.answers !== undefined || json.grading !== undefined) throw fail(`${json.answers !== undefined ? 'answers' : 'grading'}(정답 · 채점 설정)는 파일에 적지 않습니다. 채점 방식 · 답은 편집 화면에서 정합니다 (ecdk dev의 '내용 편집'에서 저장하면 ${SETTINGS_DATA_FILE}).`);
106
+ if (json.completion !== undefined) throw fail(`completion 대신 completionPolicies(지원하는 완료 정책 배열, 첫 값이 기본)를 metadata.json에 적어 주세요 (2026-11-11). ${COMPLETION_POLICIES_EXAMPLE}`);
107
+ }
108
+ /** 빌드 옵션 (package.json "ecdk" · 옛 elice.config.json 공통) */
109
+ function parseBuildOptions(json, fail) {
95
110
  for (const key of ['root', 'outDir']) {
96
111
  if (json[key] !== undefined && typeof json[key] !== 'string') throw fail(`${key}는 문자열이어야 합니다.`);
97
112
  }
98
113
  if (json.exclude !== undefined && !(Array.isArray(json.exclude) && json.exclude.every(x => typeof x === 'string'))) throw fail('exclude는 문자열 배열이어야 합니다.');
99
- // metadata.json의 screens({ learn: { enabled, entry } })와 달리 켤 화면만 파일 이름으로 적는다 (ADR 0004)
100
- if (json.screens !== undefined && !isStringRecord(json.screens)) throw fail('screens는 켤 화면만 파일 이름으로 적습니다: { "learn": "index.html", "instructor": "..." } (metadata.json의 { "enabled", "entry" } 모양과 다름).');
101
- // 오타는 metadata.json 파서와 같은 문구로 막는다 (조용히 빠지면 그 화면이 꺼진 채로 만들어짐)
102
- const unknownScreen = Object.keys(json.screens ?? {}).find(m => !rules.manifest.modes.includes(m));
103
- if (unknownScreen === 'completion' || unknownScreen === 'grading') throw fail(`완료 정책 화면의 이름은 completionPolicy입니다 (2026-11-11): screens.${unknownScreen} → "completionPolicy": "${json.screens?.[unknownScreen] ?? 'completion.html'}"`);
104
- if (unknownScreen) throw fail(`알 수 없는 화면입니다: ${unknownScreen} (가능: ${rules.manifest.modes.join(', ')})`);
105
114
  if (json.minify !== undefined && typeof json.minify !== 'boolean') throw fail('minify는 true 또는 false여야 합니다.');
106
115
  if (json.sourcemap !== undefined && typeof json.sourcemap !== 'boolean') throw fail('sourcemap은 true 또는 false여야 합니다.');
107
116
  if (json.sourcemap && !json.minify) throw fail('sourcemap은 minify와 함께 씁니다 ("minify": true). 줄이지 않으면 원본 그대로라 필요 없습니다.');
108
117
  if (json.template !== undefined && typeof json.template !== 'string') throw fail('template은 문자열이어야 합니다 (ecdk create가 적는 값).');
109
- if (json.answers !== undefined) throw fail(`answers 대신 ${GRADING_DATA_FILE}에 채점 설정을 적어 주세요 (예: { "type": "pattern", "answer_key": "^q1=b$" }). 운영에서는 편집 화면이 정합니다.`);
110
- const legacy = json;
111
- if (legacy.grading !== undefined) throw fail(`grading(채점 설정)은 elice.config.json이 아니라 ${GRADING_DATA_FILE}에 적어 주세요. 운영에서는 편집 화면이 정합니다.`);
112
- const old = json;
113
- if (old.completion !== undefined) throw fail(`completion 대신 completionPolicies(지원하는 완료 정책 배열, 첫 값이 기본)를 적어 주세요 (2026-11-11). ${COMPLETION_POLICIES_EXAMPLE}`);
118
+ const out = {};
119
+ for (const key of BUILD_OPTION_KEYS) if (json[key] !== undefined) out[key] = json[key];
120
+ return out;
121
+ }
122
+ /** package.json "ecdk": 빌드 옵션만. 플랫폼 필드는 metadata.json으로 안내한다 */
123
+ function parsePackageOptions(value) {
124
+ const fail = msg => new Error(`${PACKAGE_FILE} "${PACKAGE_CONFIG_KEY}": ${msg}`);
125
+ if (!isRecord(value)) throw fail(`객체여야 합니다. 예: { "template": "quiz@1.0.0", "minify": true }`);
126
+ rejectAnswersAndOldFields(value, fail);
127
+ const platform = Object.keys(value).filter(k => PLATFORM_KEYS.includes(k));
128
+ if (platform.length > 0) throw fail(`${platform.join(' · ')}는 원본의 metadata.json에 적습니다 (ADR 0011). package.json "ecdk"에는 빌드 옵션(${BUILD_OPTION_KEYS.join(' · ')})만.`);
129
+ const unknown = Object.keys(value).filter(k => !BUILD_OPTION_KEYS.includes(k));
130
+ if (unknown.length > 0) throw fail(`알 수 없는 키입니다: ${unknown.join(', ')} (가능: ${BUILD_OPTION_KEYS.join(', ')})`);
131
+ return {
132
+ ...defaults,
133
+ ...parseBuildOptions(value, fail),
134
+ configFile: PACKAGE_FILE
135
+ };
136
+ }
137
+ /** 옛 elice.config.json (ADR 0011 전): 빌드 옵션 + 플랫폼 필드. 플랫폼 필드는 legacy로 둔다 */
138
+ function parseLegacyConfig(raw) {
139
+ const fail = msg => new Error(`${CONFIG_FILE}: ${msg}`);
140
+ const parsed = parseJson(raw, fail);
141
+ if (!isRecord(parsed)) throw fail('객체여야 합니다.');
142
+ const json = parsed;
143
+ rejectAnswersAndOldFields(json, fail);
144
+ const options = parseBuildOptions(json, fail);
145
+ // metadata.json의 screens({ learn: { enabled, entry } })와 달리 켤 화면만 파일 이름으로 적는다 (ADR 0004)
146
+ if (json.screens !== undefined && !isStringRecord(json.screens)) throw fail('screens는 켤 화면만 파일 이름으로 적습니다: { "learn": "index.html", "instructor": "..." } (metadata.json의 { "enabled", "entry" } 모양과 다름).');
147
+ const screens = json.screens;
148
+ // 오타는 metadata.json 파서와 같은 문구로 막는다 (조용히 빠지면 그 화면이 꺼진 채로 만들어짐)
149
+ const unknownScreen = Object.keys(screens ?? {}).find(m => !rules.manifest.modes.includes(m));
150
+ if (unknownScreen === 'completion' || unknownScreen === 'grading') throw fail(`완료 정책 화면의 이름은 completionPolicy입니다 (2026-11-11): screens.${unknownScreen} → "completionPolicy": "${screens?.[unknownScreen] ?? 'completion.html'}"`);
151
+ if (unknownScreen) throw fail(`알 수 없는 화면입니다: ${unknownScreen} (가능: ${rules.manifest.modes.join(', ')})`);
152
+ const kind = json.kind;
153
+ if (kind !== undefined && kind !== 'material' && kind !== 'description') throw fail('kind는 material(자료 본문) 또는 description(문제 설명)이어야 합니다.');
154
+ let completionPolicies;
114
155
  if (json.completionPolicies !== undefined) {
115
- if (json.kind === 'description') throw fail('문제 설명(kind: description)은 완료 · 채점하지 않으므로 completionPolicies를 넣지 않습니다.');
116
- const parsed = parseCompletionPolicies(json.completionPolicies, rules);
117
- if (typeof parsed === 'string') throw fail(parsed);
118
- json.completionPolicies = parsed;
156
+ if (kind === 'description') throw fail('문제 설명(kind: description)은 완료 · 채점하지 않으므로 completionPolicies를 넣지 않습니다.');
157
+ const policies = parseCompletionPolicies(json.completionPolicies, rules);
158
+ if (typeof policies === 'string') throw fail(policies);
159
+ completionPolicies = policies;
119
160
  }
120
161
  if (json.commentary !== undefined && typeof json.commentary !== 'string') throw fail('commentary는 학습 참고 내용 파일 이름(문자열)이어야 합니다. 예: "commentary.txt"');
121
- if (json.kind !== undefined && json.kind !== 'material' && json.kind !== 'description') throw fail('kind는 material(자료 본문) 또는 description(문제 설명)이어야 합니다.');
122
162
  // 용도별로 켤 수 있는 화면은 rules.json manifest.kindModes (문제 설명은 학생 화면만)
123
- if (json.kind && json.screens) {
124
- const allowed = rules.manifest.kindModes[json.kind] ?? rules.manifest.modes;
125
- const extra = Object.keys(json.screens).filter(m => !allowed.includes(m));
126
- if (extra.length > 0) throw fail(`${json.kind === 'description' ? '문제 설명(kind: description)' : json.kind}은 ${allowed.join(' · ')} 화면만 켤 수 있습니다. screens에서 ${extra.join(', ')}를 지워 주세요.`);
163
+ if (kind && screens) {
164
+ const allowed = rules.manifest.kindModes[kind] ?? rules.manifest.modes;
165
+ const extra = Object.keys(screens).filter(m => !allowed.includes(m));
166
+ if (extra.length > 0) throw fail(`${kind === 'description' ? '문제 설명(kind: description)' : kind}은 ${allowed.join(' · ')} 화면만 켤 수 있습니다. screens에서 ${extra.join(', ')}를 지워 주세요.`);
127
167
  }
168
+ const legacy = {
169
+ ...(kind ? {
170
+ kind
171
+ } : {}),
172
+ ...(screens ? {
173
+ screens
174
+ } : {}),
175
+ ...(completionPolicies ? {
176
+ completionPolicies
177
+ } : {}),
178
+ ...(typeof json.commentary === 'string' ? {
179
+ commentary: json.commentary
180
+ } : {}),
181
+ ...(json.gradingTypes !== undefined ? {
182
+ gradingTypes: json.gradingTypes
183
+ } : {})
184
+ };
128
185
  return {
129
186
  ...defaults,
130
- ...json
187
+ ...options,
188
+ configFile: CONFIG_FILE,
189
+ legacy,
190
+ ...(kind ? {
191
+ kind
192
+ } : {}),
193
+ ...(completionPolicies ? {
194
+ completionPolicies
195
+ } : {})
196
+ };
197
+ }
198
+ /** 원본 metadata.json의 kind · completionPolicies (dev · doctor용). 없거나 형식이 틀리면 비워 두고 검사가 알린다 */
199
+ async function readManifestInfo(srcDir) {
200
+ const raw = await readOptional(join(srcDir, rules.manifest.file));
201
+ if (raw === null) return {};
202
+ const parsed = parseManifest(raw, rules);
203
+ if (!parsed.ok) return {};
204
+ const {
205
+ kind,
206
+ completionPolicies
207
+ } = parsed.manifest;
208
+ return {
209
+ ...(kind === 'material' || kind === 'description' ? {
210
+ kind
211
+ } : {}),
212
+ ...(completionPolicies ? {
213
+ completionPolicies: completionPolicies
214
+ } : {})
131
215
  };
132
216
  }
217
+ /** package.json을 읽는다 (없으면 null). JSON 형식이 틀리면 오류 */
218
+ async function readPackageJson(projectDir) {
219
+ const raw = await readOptional(join(projectDir, PACKAGE_FILE));
220
+ if (raw === null) return null;
221
+ const json = parseJson(raw, msg => new Error(`${PACKAGE_FILE}: ${msg}`));
222
+ return isRecord(json) ? json : null;
223
+ }
224
+ /**
225
+ * 프로젝트 설정 (ADR 0011): package.json "ecdk"(빌드 옵션) → 없으면 옛 elice.config.json → 없으면 기본값.
226
+ * kind · completionPolicies는 원본 metadata.json에서 읽는다 (옛 elice.config.json이면 거기서).
227
+ * 둘 다 있으면 package.json "ecdk"를 쓰고 elice.config.json은 남은 옛 파일로 경고만 한다
228
+ */
229
+ async function loadConfig(projectDir) {
230
+ const pkg = await readPackageJson(projectDir);
231
+ let config;
232
+ if (pkg && pkg[PACKAGE_CONFIG_KEY] !== undefined) config = parsePackageOptions(pkg[PACKAGE_CONFIG_KEY]);else {
233
+ const raw = await readOptional(join(projectDir, CONFIG_FILE));
234
+ if (raw !== null) return parseLegacyConfig(raw);
235
+ config = {
236
+ ...defaults
237
+ };
238
+ }
239
+ return {
240
+ ...config,
241
+ ...(await readManifestInfo(resolve(projectDir, config.root)))
242
+ };
243
+ }
244
+ /**
245
+ * 옛 elice.config.json을 metadata.json + package.json "ecdk"로 옮기는 계획 (ADR 0011). 디스크는 바꾸지 않는다.
246
+ * 플랫폼 필드는 build가 만들던 것과 같은 metadata.json으로(학습 참고 내용은 commentary.txt가 있으면), 빌드 옵션 · template은
247
+ * package.json "ecdk"로 (이미 있는 키는 그대로). 원본에 metadata.json이 이미 있는데 플랫폼 필드도 있으면 옮기지 않는다
248
+ */
249
+ async function planLegacyMigration(projectDir) {
250
+ const raw = await readFile(join(projectDir, CONFIG_FILE), 'utf8');
251
+ const config = parseLegacyConfig(raw);
252
+ const json = JSON.parse(raw);
253
+ const pkg = (await readPackageJson(projectDir)) ?? {};
254
+ const current = isRecord(pkg[PACKAGE_CONFIG_KEY]) ? pkg[PACKAGE_CONFIG_KEY] : {};
255
+ const ecdk = {};
256
+ for (const key of BUILD_OPTION_KEYS) if (json[key] !== undefined && current[key] === undefined) ecdk[key] = json[key];
257
+ const root = typeof current.root === 'string' ? current.root : config.root;
258
+ const srcDir = resolve(projectDir, root);
259
+ const legacy = config.legacy ?? {};
260
+ const dropped = legacy.gradingTypes !== undefined ? ['gradingTypes'] : [];
261
+ const hasPlatform = PLATFORM_KEYS.some(k => legacy[k] !== undefined);
262
+ const existing = await readOptional(join(srcDir, rules.manifest.file));
263
+ if (existing !== null) return hasPlatform ? {
264
+ ok: false,
265
+ reason: `원본에 ${rules.manifest.file}이 이미 있고 ${CONFIG_FILE}에도 ${PLATFORM_KEYS.filter(k => legacy[k] !== undefined).join(' · ')}가 있어 자동으로 합치지 않습니다. ${rules.manifest.file}에 직접 옮기고 ${CONFIG_FILE}을 지워 주세요.`,
266
+ ecdk,
267
+ metadata: null,
268
+ dropped
269
+ } : {
270
+ ok: true,
271
+ ecdk,
272
+ metadata: null,
273
+ dropped
274
+ };
275
+ const commentaryName = legacy.commentary ?? rules.manifest.commentaryFile;
276
+ const hasCommentary = (await readOptional(join(srcDir, commentaryName))) !== null;
277
+ const text = serializeManifest({
278
+ kind: legacy.kind,
279
+ entries: legacy.screens ?? {
280
+ learn: rules.manifest.defaultEntry
281
+ },
282
+ completionPolicies: legacy.completionPolicies,
283
+ commentary: hasCommentary ? commentaryName : undefined
284
+ }, rules);
285
+ return {
286
+ ok: true,
287
+ ecdk,
288
+ metadata: {
289
+ path: join(root, rules.manifest.file).replace(/\\/g, '/'),
290
+ text
291
+ },
292
+ dropped
293
+ };
294
+ }
295
+ /**
296
+ * 계획대로 옮긴다: metadata.json을 쓰고, package.json "ecdk"에 빌드 옵션을 더하고(package.json이 없으면 만듦),
297
+ * elice.config.json을 지운다. 옮긴 파일 목록을 돌려준다
298
+ */
299
+ async function applyLegacyMigration(projectDir, plan) {
300
+ if (!plan.ok) throw new Error(plan.reason);
301
+ const changed = [];
302
+ if (plan.metadata) {
303
+ await writeFile(join(projectDir, plan.metadata.path), plan.metadata.text);
304
+ changed.push(plan.metadata.path);
305
+ }
306
+ const pkg = (await readPackageJson(projectDir)) ?? {
307
+ name: basename(resolve(projectDir)).toLowerCase().replace(/[^a-z0-9-_.]+/g, '-'),
308
+ private: true
309
+ };
310
+ const current = isRecord(pkg[PACKAGE_CONFIG_KEY]) ? pkg[PACKAGE_CONFIG_KEY] : {};
311
+ pkg[PACKAGE_CONFIG_KEY] = {
312
+ ...plan.ecdk,
313
+ ...current
314
+ };
315
+ await writeFile(join(projectDir, PACKAGE_FILE), `${JSON.stringify(pkg, null, 2)}\n`);
316
+ changed.push(PACKAGE_FILE);
317
+ await unlink(join(projectDir, CONFIG_FILE));
318
+ return changed;
319
+ }
133
320
  /** elice.config.json에 옛 `gradingTypes`가 남아 있을 때 build · doctor가 보여 줄 경고. 없으면 null */
134
321
  function legacyGradingTypesWarning(config) {
135
- return config.gradingTypes === undefined ? null : `${CONFIG_FILE}의 gradingTypes는 더 쓰지 않습니다 (2026-11-10, 지워 주세요). 완료 정책은 completionPolicies · 완료 정책 화면(screens.completionPolicy)이, 채점 방식 · 답은 편집 화면(settings.grading)이 정하고 (ADR 0009), 로컬 채점은 ${GRADING_DATA_FILE}로 흉내 냅니다.`;
322
+ return config.legacy?.gradingTypes === undefined ? null : `${CONFIG_FILE}의 gradingTypes는 더 쓰지 않습니다 (2026-11-10, 지워 주세요). 완료 정책은 completionPolicies · 완료 정책 화면(screens.completionPolicy)이, 채점 방식 · 답은 편집 화면(settings.grading)이 정합니다 (ADR 0009).`;
136
323
  }
137
324
  /**
138
325
  * 로컬 완료 정책 (ecdk dev 흉내): `.ecdk/completion.json`(ecdk dev 완료 정책 화면이 저장)이 completionPolicies 안에
@@ -156,30 +343,49 @@ async function loadCompletionPolicy(projectDir, config) {
156
343
  }
157
344
  return first;
158
345
  }
159
- /** grading.json (없으면 null). 문제가 있으면 오류 */
160
- async function loadGradingFile(projectDir) {
346
+ /**
347
+ * `ecdk dev` 편집 화면이 저장한 settings (`.ecdk/settings.json`, 없으면 {}). 흉내 서버가 시작할 때 읽어 다시 열어도 남는다.
348
+ * 형식이 틀리면 오류
349
+ */
350
+ async function loadSavedSettings(projectDir) {
161
351
  let raw;
162
352
  try {
163
- raw = await readFile(join(projectDir, GRADING_DATA_FILE), 'utf8');
353
+ raw = await readFile(join(projectDir, SETTINGS_DATA_FILE), 'utf8');
164
354
  } catch (e) {
165
- if (e.code === 'ENOENT') return null;
355
+ if (e.code === 'ENOENT') return {};
166
356
  throw e;
167
357
  }
168
- const fail = msg => new Error(`${GRADING_DATA_FILE}: ${msg}`);
169
- const parsed = parseGrading(parseJson(raw, fail));
170
- if (typeof parsed === 'string') throw fail(parsed);
358
+ const fail = msg => new Error(`${SETTINGS_DATA_FILE}: ${msg}`);
359
+ const json = parseJson(raw, fail);
360
+ if (typeof json !== 'object' || json === null || Array.isArray(json)) throw fail('객체여야 합니다 (ecdk dev의 내용 편집이 저장한 settings).');
361
+ return json;
362
+ }
363
+ /** 저장한 settings의 grading (없으면 null). 형식이 틀리면 오류 */
364
+ function savedGrading(settings) {
365
+ if (settings.grading === undefined || settings.grading === null) return null;
366
+ const parsed = parseGrading(settings.grading);
367
+ if (typeof parsed === 'string') throw new Error(`${SETTINGS_DATA_FILE}: grading: ${parsed}`);
171
368
  return parsed;
172
369
  }
173
370
  /**
174
- * 로컬 채점 흉내용 값: 완료 정책 + grading.json. 문제 설명(채점 없음)은 undefined
371
+ * 로컬 채점 흉내용 값: 완료 정책 + `.ecdk/settings.json`의 grading. 문제 설명(채점 없음)은 undefined
175
372
  */
176
373
  async function loadGrading(projectDir, config) {
177
374
  if (config.kind === 'description') return undefined;
178
- const grading = await loadGradingFile(projectDir);
375
+ const grading = savedGrading(await loadSavedSettings(projectDir));
179
376
  return {
180
377
  completion_policy: await loadCompletionPolicy(projectDir, config),
181
378
  grading
182
379
  };
183
380
  }
381
+ /**
382
+ * 더 쓰지 않는 프로젝트 파일 (ADR 0011). 있으면 build · check가 경고(project.legacy-file)하고 옮기는 법을 알려 준다.
383
+ * content.json은 원본 폴더(root), 그 밖은 프로젝트 맨 위
384
+ */
385
+ const LEGACY_FILES = Object.freeze({
386
+ config: CONFIG_FILE,
387
+ content: 'content.json',
388
+ grading: 'grading.json'
389
+ });
184
390
 
185
- export { COMPLETION_DATA_FILE, COMPLETION_POLICIES, CONFIG_FILE, DEFAULT_COMPLETION_POLICY, GRADER_TYPES, GRADING_DATA_FILE, legacyGradingTypesWarning, loadCompletionPolicy, loadConfig, loadGrading, loadGradingFile, parseGrading };
391
+ export { BUILD_OPTION_KEYS, COMPLETION_DATA_FILE, COMPLETION_POLICIES, CONFIG_FILE, DEFAULT_COMPLETION_POLICY, GRADER_TYPES, LEGACY_FILES, PACKAGE_CONFIG_KEY, PACKAGE_FILE, PLATFORM_KEYS, SETTINGS_DATA_FILE, applyLegacyMigration, legacyGradingTypesWarning, loadCompletionPolicy, loadConfig, loadGrading, loadSavedSettings, parseGrading, planLegacyMigration, readPackageJson, savedGrading };
@@ -2,7 +2,8 @@ import { type BuildInfo } from '../rules/index.js';
2
2
  import type { SourceFile } from './collect.js';
3
3
  /**
4
4
  * metadata.json의 build. 같은 입력이면 같은 결과가 나오도록 시각 등 바뀌는 값은 넣지 않는다.
5
- * template은 ecdk create가 elice.config.json에 적은 값, sdk는 묶어 넣은 SDK 파일 머리말에서 읽는다.
5
+ * template은 ecdk create가 package.json "ecdk"에 적은 값. sdk는 zip lib/cdk.js 머리말에서 읽는다
6
+ * (build가 node_modules/@eliceio/cdk에서 넣으며 붙인 것, 옛 프로젝트는 복사본 머리말).
6
7
  */
7
8
  export declare function createBuildInfo(engine: string, extra?: {
8
9
  template?: string | undefined;
@@ -8,7 +8,8 @@ import { PROTOCOL_VERSION } from './protocol.js';
8
8
  const SDK_HEADER = /^\/\* @eliceio\/cdk (\S+)(?: \(([^)]+)\))?/;
9
9
  /**
10
10
  * metadata.json의 build. 같은 입력이면 같은 결과가 나오도록 시각 등 바뀌는 값은 넣지 않는다.
11
- * template은 ecdk create가 elice.config.json에 적은 값, sdk는 묶어 넣은 SDK 파일 머리말에서 읽는다.
11
+ * template은 ecdk create가 package.json "ecdk"에 적은 값. sdk는 zip lib/cdk.js 머리말에서 읽는다
12
+ * (build가 node_modules/@eliceio/cdk에서 넣으며 붙인 것, 옛 프로젝트는 복사본 머리말).
12
13
  */
13
14
  function createBuildInfo(engine, extra = {}) {
14
15
  const sdkFile = extra.files?.find(f => f.path === 'lib/cdk.js');
package/es/core/minify.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { transform } from 'esbuild';
2
2
 
3
3
  /**
4
- * `elice.config.json`의 `"minify": true`일 때 zip에 넣기 전에 줄인다 (용량 줄이기).
4
+ * package.json `"ecdk"`의 `"minify": true`일 때 zip에 넣기 전에 줄인다 (용량 줄이기).
5
5
  * 파일 단위 변환(번들 아님)이라 경로 · import · 파일 구성은 그대로다.
6
6
  *
7
7
  * - JS(.js · .mjs): 공백 · 주석 제거, 이름 줄이기. ES 모듈의 import/export와 top-level await는 그대로.
@@ -60,7 +60,7 @@ async function minifyFiles(files, {
60
60
  }
61
61
  } catch (e) {
62
62
  const detail = e.errors?.[0];
63
- throw new Error(`minify 실패: ${f.path}${detail?.location ? `:${detail.location.line}` : ''} ${detail?.text ?? e.message}. 문법을 확인하거나 elice.config.json의 minify를 끄세요.`);
63
+ throw new Error(`minify 실패: ${f.path}${detail?.location ? `:${detail.location.line}` : ''} ${detail?.text ?? e.message}. 문법을 확인하거나 package.json "ecdk"의 minify를 끄세요.`);
64
64
  }
65
65
  } else return f;
66
66
  const data = encoder.encode(next);
@@ -1,5 +1,5 @@
1
1
  import { type Excluded, type SourceFile } from './collect.js';
2
- import type { ContentConfig } from './config.js';
2
+ import { type ContentConfig } from './config.js';
3
3
  export interface PreparedContent {
4
4
  srcDir: string;
5
5
  outDir: string;
@@ -7,6 +7,22 @@ export interface PreparedContent {
7
7
  /** zip에 들어갈 파일 전부 (metadata.json 포함) */
8
8
  files: SourceFile[];
9
9
  excluded: Excluded[];
10
+ sdk: PreparedSdk;
11
+ }
12
+ /** SDK(@eliceio/cdk)를 어디서 넣었는지 (ADR 0010 최종 결정) */
13
+ export interface PreparedSdk {
14
+ /** package.json에 @eliceio/cdk가 있는지 */
15
+ declared: boolean;
16
+ /** 적은 범위 */
17
+ range?: string | undefined;
18
+ /** zip에 넣은 설치 버전 */
19
+ version?: string | undefined;
20
+ /** 적었는데 node_modules에 없음 (requireSdk: false일 때만, 아니면 오류) */
21
+ missing: boolean;
22
+ /** package.json에 없고 원본에 lib/cdk.js 복사본이 있는 옛 프로젝트 (sdk.lib-copy 경고) */
23
+ legacyCopy: boolean;
10
24
  }
11
25
  /** build와 doctor가 같은 결과를 보도록: 수집 → 엔진 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다. */
12
- export declare function prepareContent(projectDir: string, config: ContentConfig): Promise<PreparedContent>;
26
+ export declare function prepareContent(projectDir: string, config: ContentConfig, options?: {
27
+ requireSdk?: boolean;
28
+ }): Promise<PreparedContent>;
@@ -4,46 +4,76 @@ import 'fflate';
4
4
  import { serializeManifest } from '../rules/manifest.js';
5
5
  import { rules } from '../rules/spec.js';
6
6
  import { collectSources } from './collect.js';
7
+ import { CONFIG_FILE, PLATFORM_KEYS } from './config.js';
7
8
  import { createBuildInfo } from './manifest.js';
9
+ import { readProjectSdk, SDK_ZIP_PATH, sdkZipFile, missingSdkMessage } from './sdk.js';
8
10
 
9
11
  const isInside = (parent, child) => {
10
12
  const rel = relative(parent, child);
11
13
  return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
12
14
  };
13
15
  /** build와 doctor가 같은 결과를 보도록: 수집 → 엔진 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다. */
14
- async function prepareContent(projectDir, config) {
16
+ async function prepareContent(projectDir, config, options = {}) {
15
17
  const srcDir = resolve(projectDir, config.root);
16
18
  const outDir = resolve(projectDir, config.outDir);
17
19
  // build는 <outDir>/content/를 지우고 다시 만든다: 프로젝트 밖이나 프로젝트 폴더 자체를 가리키면 다른 데이터를 지울 수 있다
18
20
  if (!isInside(resolve(projectDir), outDir)) throw new Error(`outDir는 프로젝트 폴더 안이어야 합니다 (예: "dist"): ${config.outDir}. 밖을 가리키면 그 아래 content/를 지울 수 있어 막습니다.`);
19
21
  if (outDir === srcDir || isInside(outDir, srcDir)) throw new Error('outDir는 root와 같거나 root를 품을 수 없습니다.');
20
22
  const skipDirs = isInside(srcDir, outDir) ? [relative(srcDir, outDir).split(sep).join('/')] : [];
21
- const {
22
- files: sources,
23
- excluded
24
- } = await collectSources(srcDir, {
23
+ const collected = await collectSources(srcDir, {
25
24
  skipDirs,
26
25
  exclude: config.exclude,
27
26
  projectRoot: srcDir === resolve(projectDir)
28
27
  });
28
+ const {
29
+ excluded
30
+ } = collected;
31
+ let sources = collected.files;
32
+ // SDK: package.json에 @eliceio/cdk가 있으면 설치된 UMD 빌드를 zip lib/cdk.js로 넣는다 (원본에 옛 복사본이 있으면 대신함).
33
+ // 없으면(옛 프로젝트) 원본 lib/cdk.js 복사본을 그대로 쓰고 sdk.lib-copy로 옮기는 법을 알린다.
34
+ // dev는 설치 전에도 mock으로 열리게 requireSdk: false (실제 SDK 모드만 lib/cdk.js가 없어 실패)
35
+ const projectSdk = await readProjectSdk(projectDir);
36
+ const sdk = {
37
+ declared: projectSdk !== null,
38
+ range: projectSdk?.range,
39
+ missing: false,
40
+ legacyCopy: projectSdk === null && sources.some(f => f.path === SDK_ZIP_PATH)
41
+ };
42
+ if (projectSdk) {
43
+ const replaced = sources.some(f => f.path === SDK_ZIP_PATH);
44
+ if (replaced) {
45
+ excluded.push({
46
+ path: SDK_ZIP_PATH,
47
+ reason: 'sdk'
48
+ });
49
+ sources = sources.filter(f => f.path !== SDK_ZIP_PATH);
50
+ }
51
+ if (projectSdk.installed) {
52
+ sources = [...sources, await sdkZipFile(projectSdk.installed)];
53
+ sdk.version = projectSdk.installed.version;
54
+ } else if (options.requireSdk === false) sdk.missing = true;else throw new Error(missingSdkMessage());
55
+ }
29
56
  const engine = staticEngine;
30
57
  const files = await engine.build({
31
58
  srcDir,
32
59
  files: sources
33
60
  });
34
- // metadata.json (zip 최상위): 설정의 kind · screens로 만들고, 없으면 원본 것에 build만 채우고, 둘 다 없으면 학생 화면만
61
+ // metadata.json (zip 최상위, ADR 0011): 원본에 작성자가 쓴 것을 그대로 두고 build만 채운다.
62
+ // 원본에 없으면 옛 elice.config.json의 kind · screens로 만들고, 그것도 없으면 학생 화면만.
63
+ // build.sdk는 zip lib/cdk.js 머리말에서 (설치된 SDK를 넣었으면 그 버전)
35
64
  const build = createBuildInfo(engine.name, {
36
65
  template: config.template,
37
66
  files
38
67
  });
39
- // 학습 참고 내용: 원본 최상위 .txt 파일을 zip에 그대로 두고, metadata.json commentary에 이름만 적는다
40
- const commentaryName = (config.commentary ?? rules.manifest.commentaryFile).replace(/^\.\//, '');
68
+ // 학습 참고 내용 (만들 때만): 원본 최상위 .txt 파일을 zip에 그대로 두고, metadata.json commentary에 이름만 적는다
69
+ const legacy = config.legacy ?? {};
70
+ const commentaryName = (legacy.commentary ?? rules.manifest.commentaryFile).replace(/^\.\//, '');
41
71
  const hasCommentary = files.some(f => f.path === commentaryName);
42
- if (config.commentary !== undefined && !hasCommentary) throw new Error(`학습 참고 내용 파일이 원본 최상위에 없습니다: ${config.commentary} (elice.config.json commentary)`);
72
+ if (legacy.commentary !== undefined && !hasCommentary) throw new Error(`학습 참고 내용 파일이 원본 최상위에 없습니다: ${legacy.commentary} (${CONFIG_FILE} commentary)`);
43
73
  const commentary = hasCommentary ? commentaryName : undefined;
44
74
  const authored = files.find(f => f.path === rules.manifest.file);
45
- const fromConfig = config.screens ? 'screens' : config.kind ? 'kind' : config.completionPolicies ? 'completionPolicies' : config.commentary !== undefined ? 'commentary' : null;
46
- if (authored && fromConfig) throw new Error(`원본에 ${rules.manifest.file}이 있고 ${fromConfig}도 있습니다. 둘 중 하나만 써 주세요.`);
75
+ const fromConfig = PLATFORM_KEYS.find(k => legacy[k] !== undefined) ?? null;
76
+ if (authored && fromConfig) throw new Error(`원본에 ${rules.manifest.file}이 있고 ${CONFIG_FILE}에 ${fromConfig}도 있습니다. 둘 중 하나만 써 주세요 (ecdk doctor --fix가 ${rules.manifest.file}으로 옮김).`);
47
77
  if (authored) {
48
78
  // 형식이 틀리면 그대로 두고 검사가 알려 준다. 맞으면 다른 필드는 지키고 build만 바꾼다
49
79
  let raw = null;
@@ -57,16 +87,16 @@ async function prepareContent(projectDir, config) {
57
87
  build
58
88
  }, null, 2)}\n`);
59
89
  } else {
60
- const entries = config.screens ?? {
90
+ const entries = legacy.screens ?? {
61
91
  learn: rules.manifest.defaultEntry
62
92
  };
63
93
  files.push({
64
94
  path: rules.manifest.file,
65
95
  data: new TextEncoder().encode(serializeManifest({
66
- kind: config.kind,
96
+ kind: legacy.kind,
67
97
  // 정답은 metadata에 넣지 않는다: 편집 화면이 settings.grading에 저장. 지원하는 완료 정책만 적는다 (ADR 0009)
68
98
  entries,
69
- completionPolicies: config.completionPolicies,
99
+ completionPolicies: legacy.completionPolicies,
70
100
  commentary,
71
101
  build
72
102
  }, rules))
@@ -77,7 +107,8 @@ async function prepareContent(projectDir, config) {
77
107
  outDir,
78
108
  engine: engine.name,
79
109
  files,
80
- excluded
110
+ excluded,
111
+ sdk
81
112
  };
82
113
  }
83
114
 
@@ -1,15 +1,26 @@
1
+ import { type ContentConfig } from './config.js';
1
2
  import type { CheckOptions } from '../rules/index.js';
2
- import type { ContentConfig, GradingConfig } from './config.js';
3
+ /**
4
+ * 프로젝트에 남은 옛 파일 (ADR 0011): elice.config.json · grading.json(프로젝트 맨 위) · content.json(원본 폴더).
5
+ * 경로는 프로젝트 기준 (`/` 구분)
6
+ */
7
+ export declare function findLegacyFiles(projectDir: string, config: ContentConfig): Promise<string[]>;
8
+ /**
9
+ * 옛 lib/cdk.js 복사본 (ADR 0010 최종 결정): package.json에 @eliceio/cdk가 없는데 원본에 lib/cdk.js가 있으면 그 경로
10
+ * (프로젝트 기준). build는 복사본을 그대로 넣고 sdk.lib-copy로 옮기는 법을 알린다
11
+ */
12
+ export declare function findLegacySdkCopy(projectDir: string, config: ContentConfig): Promise<string | undefined>;
3
13
  /**
4
14
  * 프로젝트(ecdk 프로젝트 폴더)를 검사할 때 build · dev · doctor · check가 함께 쓰는 검사 옵션.
5
15
  * 파일은 prepareContent가 만든 zip 내용(원본)이고, 모듈 묶기는 build가 하므로 module-src는 보지 않는다.
6
- * 프로젝트에만 있는 정보(예: 로컬 grading.json, 템플릿 목록)를 검사에 더할 때는 이 함수에만 더한다.
16
+ * 프로젝트에만 있는 정보(예: 남은 옛 파일, 템플릿 목록)를 검사에 더할 때는 이 함수에만 더한다.
7
17
  * 그래야 `ecdk check <프로젝트>`와 `ecdk build` 결과가 어긋나지 않는다.
8
18
  *
9
- * grading: 로컬 grading.json (loadGradingFile, 없으면 null). 읽지 못했으면 undefined → grading.missing을 보지 않는다.
10
- * 문제 설명은 채점이 없어 넘기지 않는다. templates: 이 CLI가 가진 템플릿 · 버전 (build.template-unknown)
19
+ * `ecdk dev`가 쓰는 상태(.ecdk/settings.json · completion.json)는 보지 않는다: build · check 결과가 dev에서 무엇을
20
+ * 저장했는지에 따라 달라지지 않게. templates: 이 CLI가 가진 템플릿 · 버전 (build.template-unknown).
21
+ * legacyFiles: 남은 옛 파일 (project.legacy-file, elice.config.json · content.json · grading.json).
22
+ * legacySdkCopy: 옛 lib/cdk.js 복사본 (sdk.lib-copy)
11
23
  */
12
- export declare function projectCheckOptions(config: ContentConfig, extra?: {
24
+ export declare function projectCheckOptions(projectDir: string, config: ContentConfig, extra?: {
13
25
  zipBytes?: number | undefined;
14
- grading?: GradingConfig | null | undefined;
15
- }): CheckOptions;
26
+ }): Promise<CheckOptions>;