@eliceio/cdk-cli 0.1.0-alpha.2 → 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 (103) hide show
  1. package/README.md +263 -191
  2. package/es/cli.js +93 -33
  3. package/es/commands/build/index.d.ts +1 -1
  4. package/es/commands/build/index.js +21 -12
  5. package/es/commands/check/index.d.ts +11 -2
  6. package/es/commands/check/index.js +51 -5
  7. package/es/commands/create/index.d.ts +6 -0
  8. package/es/commands/create/index.js +56 -8
  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 +6 -1
  12. package/es/commands/create/scaffold.js +27 -17
  13. package/es/commands/dev/index.d.ts +1 -1
  14. package/es/commands/dev/index.js +6 -2
  15. package/es/commands/doctor/index.d.ts +21 -0
  16. package/es/commands/doctor/index.js +255 -38
  17. package/es/commands/mcp/index.d.ts +134 -0
  18. package/es/commands/mcp/index.js +399 -0
  19. package/es/commands/setup/index.d.ts +40 -0
  20. package/es/commands/setup/index.js +157 -0
  21. package/es/commands/skill/index.d.ts +2 -5
  22. package/es/commands/skill/index.js +1 -29
  23. package/es/core/collect.d.ts +5 -2
  24. package/es/core/config.d.ts +141 -31
  25. package/es/core/config.js +341 -59
  26. package/es/core/manifest.d.ts +2 -1
  27. package/es/core/manifest.js +2 -1
  28. package/es/core/minify.js +2 -2
  29. package/es/core/prepare.d.ts +18 -2
  30. package/es/core/prepare.js +47 -18
  31. package/es/core/project-check.d.ts +26 -0
  32. package/es/core/project-check.js +53 -0
  33. package/es/core/sandbox.js +2 -2
  34. package/es/core/sdk.d.ts +39 -0
  35. package/es/core/sdk.js +95 -0
  36. package/es/core/templates.d.ts +25 -0
  37. package/es/core/templates.js +41 -0
  38. package/es/dev/grading.d.ts +14 -7
  39. package/es/dev/grading.js +27 -13
  40. package/es/dev/host-page.d.ts +1 -1
  41. package/es/dev/host-page.js +34 -34
  42. package/es/dev/mock-api.d.ts +19 -4
  43. package/es/dev/mock-api.js +75 -9
  44. package/es/dev/server.d.ts +7 -0
  45. package/es/dev/server.js +112 -32
  46. package/es/rules/check.js +95 -10
  47. package/es/rules/index.d.ts +1 -1
  48. package/es/rules/index.js +1 -1
  49. package/es/rules/manifest.d.ts +23 -9
  50. package/es/rules/manifest.js +60 -35
  51. package/es/rules/node.js +3 -1
  52. package/es/rules/semver.d.ts +5 -0
  53. package/es/rules/semver.js +32 -0
  54. package/es/rules/types.d.ts +38 -7
  55. package/es/rules.json.js +2 -2
  56. package/es/test-packages.d.ts +7 -0
  57. package/guides/content-development.md +150 -55
  58. package/package.json +3 -3
  59. package/rules.json +77 -7
  60. package/skills/_shared/always.md +4 -2
  61. package/skills/elice-content-check/SKILL.md +3 -1
  62. package/skills/elice-content-create/SKILL.md +5 -4
  63. package/skills/elice-content-migrate/SKILL.md +2 -2
  64. package/skills/elice-content-publish/SKILL.md +23 -0
  65. package/templates/_shared/lib/cdk-mock.d.ts +21 -3
  66. package/templates/_shared/lib/cdk-mock.js +241 -82
  67. package/templates/_shared/lib/elice-content.css +204 -0
  68. package/templates/_shared/lib/elice-content.d.ts +115 -6
  69. package/templates/_shared/lib/elice-content.js +656 -43
  70. package/templates/blank/README.md +19 -7
  71. package/templates/blank/completion.html +15 -0
  72. package/templates/blank/gitignore +1 -0
  73. package/templates/blank/metadata.json +11 -0
  74. package/templates/blank/package.json +13 -0
  75. package/templates/blank/screens/completion.js +7 -0
  76. package/templates/blank/screens/edit.js +3 -0
  77. package/templates/blank/screens/instructor.js +12 -5
  78. package/templates/blank/screens/learn.js +16 -11
  79. package/templates/blank/template.json +6 -0
  80. package/templates/quiz/README.md +41 -31
  81. package/templates/quiz/core/behaviors.d.ts +5 -0
  82. package/templates/quiz/core/behaviors.js +12 -0
  83. package/templates/quiz/core/editor.d.ts +12 -1
  84. package/templates/quiz/core/editor.js +28 -5
  85. package/templates/quiz/core/model.d.ts +41 -1
  86. package/templates/quiz/core/model.js +272 -5
  87. package/templates/quiz/gitignore +1 -0
  88. package/templates/quiz/metadata.json +11 -0
  89. package/templates/quiz/package.json +13 -0
  90. package/templates/quiz/screens/edit.js +176 -46
  91. package/templates/quiz/screens/instructor.js +18 -12
  92. package/templates/quiz/screens/learn.js +43 -38
  93. package/templates/quiz/styles.css +47 -0
  94. package/templates/quiz/template.json +6 -0
  95. package/templates/quiz/ui/templates/edit.d.ts +3 -0
  96. package/templates/quiz/ui/templates/edit.js +53 -14
  97. package/templates/quiz/ui/texts.js +56 -29
  98. package/templates/_shared/lib/cdk.js +0 -3
  99. package/templates/blank/content.json +0 -4
  100. package/templates/blank/elice.config.json +0 -12
  101. package/templates/quiz/content.json +0 -81
  102. package/templates/quiz/elice.config.json +0 -14
  103. package/templates/quiz/grading.json +0 -13
@@ -0,0 +1,23 @@
1
+ ---
2
+ name: elice-content-publish
3
+ description: Upload an Elice Custom HTML learning material to LXP with the elice-material MCP - build the zip with ecdk, pick or create the lecture page, upload, check the draft and save it as a new version after the person approves. Use when the person asks to upload, publish, deploy or update an Elice or LXP material made with ecdk.
4
+ ---
5
+
6
+ # Upload an Elice learning material
7
+
8
+ Read `ecdk guide 12` (upload with the material MCP) first. It has the tool order, arguments and error handling.
9
+
10
+ {{always}}
11
+
12
+ ## Steps
13
+
14
+ 1. **MCP ready?** The `elice-material` tools must be available. If not, ask the person to run `ecdk setup` (QA: `ecdk mcp setup --env qa5`) and log in (Claude Code `/mcp` → elice-material → Authenticate, Helpy Code `⌘ ;`), then stop.
15
+ 2. **Build.** `ecdk build --json` must return `ok: true`. Keep `zip` and `zipBytes`.
16
+ 3. **Pick the page.** Use `.ecdk/link.json` if it exists, or the LXP edit URL the person gives (`https://{org}.…/lecturepages/{id}/edit`). Otherwise list with `list_my_organizations` → `list_courses` → `list_lectures` → `list_custom_pages` and let the person choose. Make a new page with `create_custom_page` only after the person approves.
17
+ 4. **Upload.** `get_material` (keep `current_version.id`) → `create_package_upload` with `size_bytes = zipBytes` → run its `curl_command` with `package.zip` replaced by the zip path → `submit_package` → poll `get_draft` until ready or failed. On failure, report the server's reason with `ecdk check dist/content.zip` and stop.
18
+ 5. **Approve.** Show what changes (page, title, completion policy, and that the content and answers are entered on the LXP edit screen after saving) and the draft `preview_urls`. Saving is visible to learners at once if the page is open. Wait for an explicit yes.
19
+ 6. **Save.** `save_draft` with `expected_current_version_id` and `completion_policy`. Do not send content or `grading` from `.ecdk/settings.json`: it is sample input for local checks only and is never uploaded. On `MATERIAL_CHANGED`, stop: someone saved in between. A quiz (`on_graded`) has no answers at its first upload; the server's behavior there is undecided (G132): if it returns `MATERIAL_GRADING_REQUIRED`, stop and tell the person.
20
+ 7. **Content and answers.** Tell the person to open the LXP edit screen now and enter the content and answers (a quiz needs its answers right away to be graded). Until then learners see "아직 내용이 없습니다".
21
+ 8. **Finish.** Set the title and icon with `update_material` if the page has none (`ecdk guide 12`). Write `.ecdk/link.json` as `{ "org": …, "lecture_page_id": …, "version_id": … }` so the next upload goes to the same page. Report the LXP URL. New pages stay closed until the person opens them in LXP.
22
+
23
+ {{version}}
@@ -1,7 +1,8 @@
1
1
  // lib/cdk-mock.js 타입 (편집기 자동완성용)
2
2
  export type Scope = 'learn' | 'edit';
3
3
  export type Viewer = 'student' | 'instructor' | 'tutor';
4
- export type Screen = 'learn' | 'instructor' | 'edit';
4
+ export type Screen = 'learn' | 'instructor' | 'edit' | 'completionPolicy';
5
+ export type CompletionPolicy = 'on_access' | 'on_submit' | 'on_graded';
5
6
 
6
7
  export declare const ErrorCode: Readonly<{
7
8
  Init: 'init';
@@ -19,6 +20,7 @@ export declare const ErrorCode: Readonly<{
19
20
  ExternalServiceError: 'external_service_error';
20
21
  NavigationTimeout: 'navigation_timeout';
21
22
  RequestFailed: 'request_failed';
23
+ DraftNotSaved: 'draft_not_saved';
22
24
  }>;
23
25
  export declare class EliceCDKError extends Error {
24
26
  static code: typeof ErrorCode;
@@ -40,7 +42,16 @@ export interface Submission extends SubmitResult {
40
42
  answer: unknown;
41
43
  }
42
44
 
43
- export declare function gradeLocally(grading: unknown, answer: unknown): SubmitResult;
45
+ /** 채점 설정을 서버 모양으로 ({ type: pattern | rubric }). camelCase answerKey도 받는다. 채점 방식이 아니면 null */
46
+ export declare function normalizeGradingSettings(
47
+ grading: unknown
48
+ ): { type: 'pattern'; answer_key?: string } | { type: 'rubric'; rubric?: string } | null;
49
+ /** 완료 정책(없으면 채점 설정이 있으면 on_graded, 없으면 on_submit)과 채점 설정으로 로컬 채점 */
50
+ export declare function gradeLocally(
51
+ grading: unknown,
52
+ answer: unknown,
53
+ policy?: 'on_access' | 'on_submit' | 'on_graded'
54
+ ): SubmitResult;
44
55
 
45
56
  export interface Navigation {
46
57
  previous(): void;
@@ -55,6 +66,8 @@ export declare class MockEliceCDK {
55
66
  onSessionExpired?: () => void;
56
67
  scenario?: string;
57
68
  grading?: unknown;
69
+ completionPolicy?: CompletionPolicy;
70
+ completionPolicies?: CompletionPolicy[];
58
71
  settings?: Record<string, unknown>;
59
72
  loadJson?: (url: string) => Promise<unknown>;
60
73
  delayMs?: number;
@@ -78,6 +91,8 @@ export declare class MockEliceCDK {
78
91
  description: unknown;
79
92
  entries: Partial<Record<Screen, string>>;
80
93
  settings: Record<string, unknown>;
94
+ completionPolicy: CompletionPolicy;
95
+ completionPolicies: CompletionPolicy[] | null;
81
96
  } | null;
82
97
  readonly result: {
83
98
  score: number | null;
@@ -88,7 +103,10 @@ export declare class MockEliceCDK {
88
103
  init(options?: { hash?: string; pathname?: string }): Promise<this>;
89
104
  submit(answer: unknown): Promise<SubmitResult>;
90
105
  history(options?: { offset?: number; limit?: number }): Promise<Submission[]>;
91
- saveSettings(settings: Record<string, unknown>): void;
106
+ /** 저장하고 부모 창에 settings-saved로 알린다. 토큰 없는 draft(#edit=1)는 draft_not_saved로 거절 */
107
+ saveSettings(settings: Record<string, unknown>): Promise<void>;
108
+ /** 완료 정책 화면에서만. 이 브라우저에 남기고 settings-saved로 알린다. draft는 draft_not_saved, 채점 설정 없는 on_graded는 거절 */
109
+ saveCompletionPolicy(policy: CompletionPolicy): Promise<void>;
92
110
  dispose(): void;
93
111
  reset(): void;
94
112
  }
@@ -2,14 +2,22 @@
2
2
  * @eliceio/cdk 1.x(EliceCDK)와 같은 공개 인터페이스를 가진 mock · 템플릿이 제공 (고치지 마세요)
3
3
  *
4
4
  * 서버 없이 화면을 시험할 때 키트가 대신 씁니다. 실제 SDK와 다른 점:
5
- * - 채점: 프로젝트의 grading.json(유형 · 정답 · 채점 기준, 유형이 없으면 elice.config.json gradingTypes의 첫 유형)으로 로컬 채점 (없으면 제출하면 100점)
5
+ * - 채점: 편집 화면이 저장한 채점 설정(settings.grading { type: pattern | rubric })과 완료 정책으로 로컬 채점.
6
+ * pattern 답은 정규식 하나, 답 문자열 전체 일치. 프로젝트 폴더를 그대로 열면 ecdk dev가 저장한 .ecdk/settings.json으로 시작
7
+ * - 완료 정책: material.completionPolicy · completionPolicies와 saveCompletionPolicy를 흉내 낸다. 지원하는 정책은
8
+ * metadata completionPolicies(프로젝트의 metadata.json · ecdk dev가 주는 값)이고, 처음 값은
9
+ * .ecdk/completion.json(그 안에 있을 때) · 없으면 첫 값(서버가 업로드 때 정하는 값). 바꾼 값은 이 브라우저에만
6
10
  * - 저장: 설정 화면이 저장한 내용과 제출 기록을 브라우저에 남겨 다른 화면에서도 보임
7
11
  * (sandbox라 저장소가 막히면 이 페이지 안에서만)
8
12
  * - 보는 사람: 주소에 #viewer=student | instructor | tutor (mock 전용, 기본 student)
9
- * #preview=1 · #edit=1은 실제 SDK처럼 토큰 없는 draft (viewer는 instructor)
13
+ * #preview=1 · #edit=1은 실제 SDK처럼 토큰 없는 draft (viewer는 instructor, 편집 저장은 draft_not_saved)
14
+ * - 편집 화면: #scope=edit (mock 전용) = 저장된 버전을 edit 토큰으로 연 편집 화면. saveSettings가 저장된다
15
+ * 편집 화면이 넣은 settings.grading은 학생 화면의 material.settings에서 서버처럼 빼고 준다
16
+ * - 완료 정책 화면: #scope=edit&screen=completionPolicy (mock 전용). saveCompletionPolicy가 저장된다.
17
+ * #completionPolicy=1은 토큰 없는 draft (저장은 draft_not_saved)
10
18
  * - 수업 페이지 이동: 아무 데도 가지 않고, 이전·다음 페이지는 없음(false)
11
19
  * - 시나리오: 주소에 ?mock=session_expired | rate_limited | request_failed | external_service_error
12
- * | slow | content_not_ready | unauthorized
20
+ * | slow | content_not_ready | unauthorized | material_changed
13
21
  *
14
22
  * 실제 SDK: @eliceio/cdk 1.x (eliceio-cdk-v2 feat/PLAT-4973-monorepo) 기준
15
23
  */
@@ -30,6 +38,7 @@ export const ErrorCode = Object.freeze({
30
38
  ExternalServiceError: 'external_service_error',
31
39
  NavigationTimeout: 'navigation_timeout',
32
40
  RequestFailed: 'request_failed',
41
+ DraftNotSaved: 'draft_not_saved',
33
42
  });
34
43
 
35
44
  export class EliceCDKError extends Error {
@@ -44,12 +53,13 @@ const VIEWERS = Object.freeze(['student', 'instructor', 'tutor']);
44
53
  const MAX_ANSWER_BYTES = 64 * 1024;
45
54
  const STORE_PREFIX = 'elice-content-mock:';
46
55
  const MESSAGE_SOURCE = 'eliceio-content-sdk';
47
- const SETTINGS_MESSAGE_TYPE = 'settings-change';
48
- /** 템플릿의 metadata.json 진입 파일 (elice.config.json `screens`가 있으면 그것) */
56
+ const SETTINGS_SAVED_MESSAGE_TYPE = 'settings-saved';
57
+ /** 템플릿의 metadata.json 진입 파일 */
49
58
  const DEFAULT_ENTRIES = Object.freeze({
50
59
  learn: 'index.html',
51
60
  instructor: 'instructor.html',
52
61
  edit: 'edit.html',
62
+ completionPolicy: 'completion.html',
53
63
  });
54
64
  /** rubric(AI) 채점 흉내 점수 */
55
65
  const RUBRIC_MOCK_SCORE = 80;
@@ -89,49 +99,74 @@ function parseHash(hash) {
89
99
  token: params.get('token'),
90
100
  preview: params.get('preview'),
91
101
  edit: params.get('edit'),
102
+ completionPolicy: params.get('completionPolicy'),
92
103
  viewer: params.get('viewer'),
104
+ scope: params.get('scope'),
105
+ screen: params.get('screen'),
93
106
  };
94
107
  }
95
108
 
96
- const normalize = (v) =>
97
- typeof v === 'string'
98
- ? v.trim().toLowerCase()
99
- : Array.isArray(v)
100
- ? v.map(normalize).sort()
101
- : v && typeof v === 'object'
102
- ? Object.fromEntries(
103
- Object.keys(v)
104
- .sort()
105
- .map((k) => [k, normalize(v[k])]),
106
- )
107
- : v;
109
+ /** 정답 비교에 쓰는 답 문자열: 문자열은 앞뒤 공백을 자르고, 그 밖은 JSON으로 */
110
+ const answerText = answer =>
111
+ typeof answer === 'string' ? answer.trim() : JSON.stringify(answer ?? null);
112
+
113
+ /** 완료 정책 값 (서버 material_version.completion_policy) */
114
+ const POLICIES = Object.freeze(['on_access', 'on_submit', 'on_graded']);
115
+
116
+ /**
117
+ * 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }`.
118
+ * camelCase(answerKey)도 받는다. 채점 방식이 아니면 null
119
+ */
120
+ export function normalizeGradingSettings(grading) {
121
+ if (!grading || typeof grading !== 'object') return null;
122
+ if (grading.type === 'pattern') {
123
+ const answerKey = grading.answer_key ?? grading.answerKey;
124
+ return { type: 'pattern', ...(typeof answerKey === 'string' ? { answer_key: answerKey } : {}) };
125
+ }
126
+ if (grading.type === 'rubric')
127
+ return { type: 'rubric', ...(typeof grading.rubric === 'string' ? { rubric: grading.rubric } : {}) };
128
+ return null;
129
+ }
108
130
 
109
131
  /**
110
- * elice-material `grading` 흉내: on_access · on_submit · pattern(exact | regex) · rubric · manual · none.
111
- * 실제 서버처럼 요청 안에서 바로 채점한 `{ isCorrect, score }`만 돌려준다.
112
- * pattern exact는 서버처럼 답 전체를 한 번에 비교한다 (부분 점수 없음).
113
- * rubric(AI 채점)은 바로 80점으로 흉내 내고, manual · none · on_access는 점수가 없다(null).
132
+ * elice-material 채점 흉내 (완료 정책 → 채점 방식 → 점수). 실제 서버처럼 요청 안에서 바로 채점한
133
+ * `{ isCorrect, score }`만 돌려준다. isCorrect는 완료(통과) 여부.
134
+ * - on_access: 점수 없음(null) · on_submit: 100
135
+ * - on_graded + pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞으면 100, 아니면 0
136
+ * - on_graded + rubric: 바로 80점으로 흉내, 통과로 봄 (통과 기준 pass_threshold는 정해지지 않음, G136)
137
+ * @param {object | null} grading settings.grading
138
+ * @param {unknown} answer
139
+ * @param {string} [policy] 완료 정책. 없으면 채점 설정이 있으면 on_graded, 없으면 on_submit
114
140
  */
115
- export function gradeLocally(grading, answer) {
116
- const type = grading?.type ?? 'on_submit';
117
- if (type === 'on_submit') return { isCorrect: true, score: 100 };
118
- if (type === 'pattern') {
119
- let ok;
120
- if (grading.match === 'regex') ok = new RegExp(String(grading.answer_key)).test(String(answer));
121
- else ok = JSON.stringify(normalize(answer)) === JSON.stringify(normalize(grading.answer_key));
141
+ export function gradeLocally(grading, answer, policy) {
142
+ const g = normalizeGradingSettings(grading);
143
+ const p = policy ?? (g ? 'on_graded' : 'on_submit');
144
+ if (p === 'on_submit') return { isCorrect: true, score: 100 };
145
+ if (p !== 'on_graded') return { isCorrect: null, score: null };
146
+ if (g?.type === 'pattern') {
147
+ let ok = false;
148
+ try {
149
+ ok =
150
+ typeof g.answer_key === 'string' &&
151
+ new RegExp(`^(?:${g.answer_key})$`).test(answerText(answer));
152
+ } catch {
153
+ ok = false;
154
+ }
122
155
  return { isCorrect: ok, score: ok ? 100 : 0 };
123
156
  }
124
- if (type === 'rubric') return { isCorrect: true, score: RUBRIC_MOCK_SCORE };
157
+ if (g?.type === 'rubric') return { isCorrect: true, score: RUBRIC_MOCK_SCORE };
125
158
  return { isCorrect: null, score: null };
126
159
  }
127
160
 
128
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
161
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
129
162
 
130
163
  /**
131
164
  * @typedef {object} MockOptions
132
165
  * @property {() => void} [onSessionExpired]
133
166
  * @property {string} [scenario] ?mock= 대신 직접 지정
134
- * @property {object} [grading] elice.config.json 대신 직접 지정
167
+ * @property {object} [grading] 채점 설정 직접 지정 (settings.grading 모양, 테스트용)
168
+ * @property {'on_access' | 'on_submit' | 'on_graded'} [completionPolicy] 로컬 완료 정책 대신 직접 지정
169
+ * @property {Array<'on_access' | 'on_submit' | 'on_graded'>} [completionPolicies] metadata completionPolicies 대신 직접 지정
135
170
  * @property {Record<string, unknown>} [settings] 처음 저장된 내용
136
171
  * @property {(url: string) => Promise<unknown>} [loadJson] 테스트용
137
172
  * @property {number} [delayMs] 응답 지연 (scenario=slow면 1500)
@@ -148,6 +183,9 @@ export class MockEliceCDK {
148
183
  #screen = null;
149
184
  #entries = DEFAULT_ENTRIES;
150
185
  #grading = null;
186
+ #policy = null;
187
+ /** metadata completionPolicies (없으면 null) */
188
+ #policies = null;
151
189
  #account = null;
152
190
  #metadata = null;
153
191
  #isDraft = false;
@@ -165,8 +203,15 @@ export class MockEliceCDK {
165
203
  this.#assertScreen('learn', 'instructor');
166
204
  };
167
205
  this.#navigation = Object.freeze({
168
- previous: () => assertNavigable(),
169
- next: () => assertNavigable(),
206
+ // 로컬에는 수업이 없어 이동하지 않는다. 화면이 부른 것만 콘솔에 남긴다 (ecdk dev는 실제 SDK + 호스트 기록)
207
+ previous: () => {
208
+ assertNavigable();
209
+ console.info('[mock] navigation.previous(): 이전 수업 자료로 이동 (로컬은 이동하지 않음)');
210
+ },
211
+ next: () => {
212
+ assertNavigable();
213
+ console.info('[mock] navigation.next(): 다음 수업 자료로 이동 (로컬은 이동하지 않음)');
214
+ },
170
215
  navigate: (_lecturePageId) => assertNavigable(),
171
216
  getHasPrevious: async () => {
172
217
  assertNavigable();
@@ -209,10 +254,15 @@ export class MockEliceCDK {
209
254
  }
210
255
  get material() {
211
256
  if (!this.initialized) return null;
257
+ // 서버처럼 학생 · 튜터 · 교육자(learn scope)에게는 settings.grading(정답)을 빼고 준다
258
+ const { grading: _saved, ...rest } = this.#store.get('settings', {});
259
+ const effective = this.#effectiveGrading();
212
260
  return {
213
261
  description: { type: 'text', text: '' },
214
262
  entries: this.#entries,
215
- settings: this.#store.get('settings', {}),
263
+ settings: this.#scope === 'edit' && effective ? { ...rest, grading: effective } : rest,
264
+ completionPolicy: this.#effectivePolicy(),
265
+ completionPolicies: this.#policies,
216
266
  };
217
267
  }
218
268
  get result() {
@@ -236,28 +286,50 @@ export class MockEliceCDK {
236
286
  if (this.#scenario === 'unauthorized')
237
287
  throw new EliceCDKError(ErrorCode.Unauthorized, 'Invalid token (mock).');
238
288
 
239
- const isDraft = params.token == null && (params.preview === '1' || params.edit === '1');
289
+ const isDraft =
290
+ params.token == null &&
291
+ (params.preview === '1' || params.edit === '1' || params.completionPolicy === '1');
240
292
  // 실제 SDK: draft는 instructor가 본다. 토큰이 있는 경우를 흉내 낼 때만 #viewer=로 고른다
241
- const viewer = isDraft ? 'instructor' : (params.viewer ?? 'student');
293
+ const editScope =
294
+ params.edit === '1' || params.completionPolicy === '1' || params.scope === 'edit';
295
+ const completionScreen =
296
+ params.completionPolicy === '1' ||
297
+ (params.scope === 'edit' && params.screen === 'completionPolicy');
298
+ const viewer = isDraft || editScope ? 'instructor' : (params.viewer ?? 'student');
242
299
  if (!VIEWERS.includes(viewer))
243
300
  throw new EliceCDKError(ErrorCode.InvalidParam, `Unknown viewer: ${viewer}`);
244
301
 
245
302
  if (this.#options.settings && Object.keys(this.#store.get('settings', {})).length === 0)
246
303
  this.#store.set('settings', this.#options.settings);
247
- const config = this.#options.grading ? null : await this.#loadConfig();
248
- this.#grading = this.#options.grading ?? config ?? null;
249
- this.#entries = config?.screens ?? DEFAULT_ENTRIES;
304
+ const local = await this.#loadLocal();
305
+ if (local.settings && Object.keys(this.#store.get('settings', {})).length === 0)
306
+ this.#store.set('settings', local.settings);
307
+ this.#grading = normalizeGradingSettings(this.#options.grading) ?? local.grading;
308
+ const policies = this.#options.completionPolicies ?? local.policies;
309
+ this.#policies = policies;
310
+ // 이 브라우저에 저장한 값은 지원하는 정책 안에 있을 때만. null이면 채점 설정이 있으면 on_graded,
311
+ // 없으면 on_submit (#effectivePolicy)
312
+ const stored = this.#store.get('completionPolicy', null);
313
+ this.#policy =
314
+ this.#options.completionPolicy ??
315
+ (POLICIES.includes(stored) && (!policies || policies.includes(stored)) ? stored : null) ??
316
+ local.policy ??
317
+ policies?.[0] ??
318
+ null;
319
+ this.#entries = DEFAULT_ENTRIES;
250
320
 
251
321
  this.#isDraft = isDraft;
252
322
  this.#isSessionExpired = false;
253
323
  this.#draftSubmissions = [];
254
324
  this.#viewer = viewer;
255
- this.#scope = params.edit === '1' ? 'edit' : 'learn';
325
+ this.#scope = editScope ? 'edit' : 'learn';
256
326
  // 실제 SDK와 같은 규칙: edit scope면 edit, 교육자이고 교육자 진입 파일이 있으면 instructor, 그 밖은 learn.
257
327
  // draft는 fragment가 화면을 알려 준다 (#edit=1이면 edit, 아니면 learn)
258
328
  this.#screen =
259
329
  this.#scope === 'edit'
260
- ? 'edit'
330
+ ? completionScreen
331
+ ? 'completionPolicy'
332
+ : 'edit'
261
333
  : !isDraft && viewer === 'instructor' && this.#entries.instructor
262
334
  ? 'instructor'
263
335
  : 'learn';
@@ -274,7 +346,7 @@ export class MockEliceCDK {
274
346
  this.initialized = true;
275
347
  // "들어오면 완료": 학생이 처음 열면 서버가 100점으로 기록한다
276
348
  if (
277
- this.#grading?.type === 'on_access' &&
349
+ this.#effectivePolicy() === 'on_access' &&
278
350
  viewer === 'student' &&
279
351
  !isDraft &&
280
352
  this.#store.get('result', null) === null
@@ -285,10 +357,13 @@ export class MockEliceCDK {
285
357
  completedAt: new Date().toISOString(),
286
358
  });
287
359
  if (this.#scenario === 'session_expired') {
288
- setTimeout(() => {
289
- this.#isSessionExpired = true;
290
- this.#options.onSessionExpired?.();
291
- }, 0);
360
+ setTimeout(
361
+ () => {
362
+ this.#isSessionExpired = true;
363
+ this.#options.onSessionExpired?.();
364
+ },
365
+ 0
366
+ );
292
367
  }
293
368
  return this;
294
369
  }
@@ -312,7 +387,7 @@ export class MockEliceCDK {
312
387
  throw new EliceCDKError(ErrorCode.InvalidInput, 'Answer is over 64KB.');
313
388
  await this.#delay();
314
389
 
315
- const res = gradeLocally(this.#grading, answer);
390
+ const res = gradeLocally(this.#effectiveGrading(), answer, this.#effectivePolicy());
316
391
  if (this.#isDraft) this.#draftSubmissions.unshift(this.#submission(answer, res, 'preview'));
317
392
  else if (this.#viewer === 'student') this.#record(res, answer);
318
393
  return res;
@@ -322,36 +397,92 @@ export class MockEliceCDK {
322
397
  this.#assertReady();
323
398
  await this.#delay();
324
399
  const { offset = 0, limit = 20 } = options;
325
- const submissions = this.#isDraft
326
- ? this.#draftSubmissions
327
- : this.#store.get('submissions', []);
400
+ const submissions = this.#isDraft ? this.#draftSubmissions : this.#store.get('submissions', []);
328
401
  return submissions.slice(offset, offset + limit);
329
402
  }
330
403
 
331
404
  /**
332
- * 설정 화면(screen edit)에서만. 실제 SDK처럼 편집 페이지(부모 창)에 postMessage로 넘기고,
333
- * mock은 브라우저에도 남겨 다른 화면의 `material.settings`로 보이게 한다.
405
+ * 완료 정책 화면(screen completionPolicy)에서만. 실제 SDK처럼 지금 버전의 완료 정책을 바꾸고(mock은 이 브라우저에만)
406
+ * 결과를 편집 페이지에 `settings-saved`로 알린다. 토큰 없는 draft(#completionPolicy=1)는 draft_not_saved,
407
+ * 채점 설정 없는 on_graded는 서버처럼 MATERIAL_GRADING_REQUIRED(request_failed의 cause)로 거절
408
+ * @param {'on_access' | 'on_submit' | 'on_graded'} policy
409
+ */
410
+ async saveCompletionPolicy(policy) {
411
+ this.#assertReady();
412
+ this.#assertScreen('completionPolicy');
413
+ await this.#delay();
414
+ try {
415
+ if (this.#isDraft)
416
+ throw new EliceCDKError(
417
+ ErrorCode.DraftNotSaved,
418
+ 'The completion policy of an unsaved upload cannot be saved (mock).'
419
+ );
420
+ if (!POLICIES.includes(policy))
421
+ throw new EliceCDKError(ErrorCode.InvalidInput, `Unknown completion policy: ${policy}`);
422
+ if (policy === 'on_graded' && !this.#effectiveGrading())
423
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Grading is required (mock).', {
424
+ cause: { code: 'MATERIAL_GRADING_REQUIRED' },
425
+ });
426
+ if (this.#scenario === 'material_changed')
427
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Material changed (mock).', {
428
+ cause: { code: 'MATERIAL_CHANGED' },
429
+ });
430
+ this.#policy = policy;
431
+ this.#store.set('completionPolicy', policy);
432
+ this.#postSettingsSaved({ status: 'saved' });
433
+ } catch (err) {
434
+ const code = err.cause?.cause?.code ?? err.code;
435
+ this.#postSettingsSaved({ status: 'failed', code });
436
+ throw err;
437
+ }
438
+ }
439
+
440
+ /**
441
+ * 편집 화면(screen edit)에서만. 실제 SDK처럼 저장하고(mock은 브라우저에 남겨 다른 화면의 `material.settings`로 보임)
442
+ * 결과를 편집 페이지(부모 창)에 `settings-saved`로 알린다. 토큰 없는 draft(#edit=1)는 `draft_not_saved`로 거절.
443
+ * 시나리오 ?mock=material_changed면 다른 사람이 먼저 저장한 것처럼 실패한다 (실제 SDK: request_failed, 서버 코드는 cause)
334
444
  */
335
- saveSettings(settings) {
445
+ async saveSettings(settings) {
336
446
  this.#assertReady();
337
447
  this.#assertScreen('edit');
338
- this.#store.set('settings', settings);
339
- const parent = globalThis.parent;
340
- if (parent && parent !== globalThis && typeof parent.postMessage === 'function') {
341
- // sandbox(출처 null)라 부모 출처를 알 수 없어 실제 SDK도 '*'로 보낸다. 편집 페이지가 event.source로 확인
342
- // ecdk-ignore-next-line sec.postmessage-wildcard
343
- parent.postMessage(
344
- {
345
- source: MESSAGE_SOURCE,
346
- type: SETTINGS_MESSAGE_TYPE,
347
- materialId: this.#metadata.materialId,
348
- payload: { settings },
349
- },
350
- '*',
351
- );
448
+ await this.#delay();
449
+ try {
450
+ if (this.#isDraft)
451
+ throw new EliceCDKError(
452
+ ErrorCode.DraftNotSaved,
453
+ 'Settings of an unsaved upload cannot be saved (mock).'
454
+ );
455
+ if (this.#scenario === 'material_changed')
456
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Material changed (mock).', {
457
+ cause: { code: 'MATERIAL_CHANGED' },
458
+ });
459
+ if (this.#scenario === 'request_failed')
460
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Network error (mock).');
461
+ this.#store.set('settings', settings);
462
+ this.#postSettingsSaved({ status: 'saved' });
463
+ } catch (err) {
464
+ const code = err.cause?.cause?.code ?? err.code;
465
+ this.#postSettingsSaved({ status: 'failed', code });
466
+ throw err;
352
467
  }
353
468
  }
354
469
 
470
+ #postSettingsSaved(payload) {
471
+ const parent = globalThis.parent;
472
+ if (!parent || parent === globalThis || typeof parent.postMessage !== 'function') return;
473
+ // sandbox(출처 null)라 부모 출처를 알 수 없어 실제 SDK도 '*'로 보낸다. 편집 페이지가 event.source로 확인
474
+ // ecdk-ignore-next-line sec.postmessage-wildcard
475
+ parent.postMessage(
476
+ {
477
+ source: MESSAGE_SOURCE,
478
+ type: SETTINGS_SAVED_MESSAGE_TYPE,
479
+ materialId: this.#metadata.materialId,
480
+ payload,
481
+ },
482
+ '*'
483
+ );
484
+ }
485
+
355
486
  /** 실제 SDK: 토큰 자동 갱신을 멈춘다. mock은 갱신이 없어 아무것도 하지 않는다 */
356
487
  dispose() {}
357
488
 
@@ -360,9 +491,20 @@ export class MockEliceCDK {
360
491
  this.#store.set('settings', {});
361
492
  this.#store.set('submissions', []);
362
493
  this.#store.set('result', null);
494
+ this.#store.set('completionPolicy', null);
363
495
  this.#draftSubmissions = [];
364
496
  }
365
497
 
498
+ /** 저장된 채점 설정(편집 화면), 없으면 ecdk dev가 주는 값 · options.grading */
499
+ #effectiveGrading() {
500
+ return normalizeGradingSettings(this.#store.get('settings', {}).grading) ?? this.#grading;
501
+ }
502
+
503
+ /** 정해진 완료 정책, 없으면 채점 설정이 있으면 on_graded · 없으면 on_submit */
504
+ #effectivePolicy() {
505
+ return this.#policy ?? (this.#effectiveGrading() ? 'on_graded' : 'on_submit');
506
+ }
507
+
366
508
  #assertReady() {
367
509
  if (!this.initialized) throw new EliceCDKError(ErrorCode.NotInitialized, 'Call init() first.');
368
510
  if (this.#isSessionExpired)
@@ -373,7 +515,7 @@ export class MockEliceCDK {
373
515
  if (!screens.includes(this.#screen))
374
516
  throw new EliceCDKError(
375
517
  ErrorCode.ScreenNotSupported,
376
- `This call is only available on the ${screens.join(' or ')} screen.`,
518
+ `This call is only available on the ${screens.join(' or ')} screen.`
377
519
  );
378
520
  }
379
521
 
@@ -396,7 +538,8 @@ export class MockEliceCDK {
396
538
  this.#store.set('submissions', submissions);
397
539
  const prev = this.#store.get('result', null);
398
540
  const score = res.score ?? prev?.score ?? null;
399
- const completed = res.score === 100 || this.#grading?.type === 'none';
541
+ // 완료는 통과(isCorrect)로: on_submit · pattern 100점 · rubric 흉내 점수
542
+ const completed = res.isCorrect === true;
400
543
  this.#store.set('result', {
401
544
  score,
402
545
  submitCount: (prev?.submitCount ?? 0) + 1,
@@ -404,22 +547,38 @@ export class MockEliceCDK {
404
547
  });
405
548
  }
406
549
 
407
- async #loadConfig() {
550
+ /**
551
+ * 로컬 채점 설정 · 완료 정책. ecdk dev의 콘텐츠 주소를 직접 열면 dev가 주는 값을, 프로젝트 폴더를 그대로 열면
552
+ * .ecdk/settings.json(ecdk dev 편집 화면이 저장한 내용 + 답) · .ecdk/completion.json과 completionPolicies(metadata.json)를
553
+ * 읽는다 (.ecdk는 zip에서 빠짐, 로컬 채점용으로 일부러 읽음). 완료 정책은 .ecdk(목록 안일 때) > 첫 값
554
+ * @returns {Promise<{ grading: object | null, policy: string | null, policies: string[] | null, settings?: object | null }>}
555
+ */
556
+ async #loadLocal() {
408
557
  const loadJson =
409
- this.#options.loadJson ?? ((url) => fetch(url).then((r) => (r.ok ? r.json() : null)));
410
- // ecdk dev의 콘텐츠 주소를 직접 열었을 때: 설정 파일은 zip처럼 빠져 있으니 dev가 주는 로컬 채점 설정을 쓴다
558
+ this.#options.loadJson ?? (url => fetch(url).then(r => (r.ok ? r.json() : null)));
559
+ const listOf = v => (Array.isArray(v) && v.length > 0 && v.every(p => POLICIES.includes(p)) ? v : null);
411
560
  const devGrading = globalThis.__ECDK_DEV__?.grading;
412
- if (typeof devGrading === 'string') return loadJson(devGrading).catch(() => null);
413
- // 프로젝트 폴더를 그대로 열면 elice.config.json · grading.json이 있다 (zip에서는 빠짐). 로컬 채점용으로 일부러 읽는다.
414
- // 지원 유형은 elice.config.json gradingTypes, 흉내 낼 유형 · 정답은 grading.json (유형이 없으면 지원 유형의 첫 번째)
415
- // ecdk-ignore-next-line project.answer-import
416
- const config = await loadJson('elice.config.json').catch(() => null);
417
- const supported = Array.isArray(config?.gradingTypes) ? config.gradingTypes : [];
418
- if (supported.length === 0) return null;
561
+ if (typeof devGrading === 'string') {
562
+ const dev = await loadJson(devGrading).catch(() => null);
563
+ return {
564
+ grading: normalizeGradingSettings(dev?.grading),
565
+ policy: POLICIES.includes(dev?.completion_policy) ? dev.completion_policy : null,
566
+ policies: listOf(dev?.completion_policies),
567
+ };
568
+ }
569
+ if (this.#options.grading) return { grading: null, policy: null, policies: null };
419
570
  // ecdk-ignore-next-line project.answer-import
420
- const data = await loadJson('grading.json').catch(() => null);
421
- const grading = data && typeof data === 'object' ? data : {};
422
- return { ...grading, type: supported.includes(grading.type) ? grading.type : supported[0] };
571
+ const saved = await loadJson('.ecdk/settings.json').catch(() => null);
572
+ const local = await loadJson('.ecdk/completion.json').catch(() => null);
573
+ const manifest = await loadJson('metadata.json').catch(() => null);
574
+ const policies = listOf(manifest?.completionPolicies);
575
+ const savedPolicy = local?.completion_policy;
576
+ return {
577
+ grading: null,
578
+ policy: policies?.includes(savedPolicy) ? savedPolicy : (policies?.[0] ?? null),
579
+ policies,
580
+ settings: saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : null,
581
+ };
423
582
  }
424
583
 
425
584
  async #delay() {