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

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 (92) hide show
  1. package/README.md +171 -136
  2. package/es/cli.js +119 -26
  3. package/es/commands/build/index.d.ts +4 -1
  4. package/es/commands/build/index.js +28 -9
  5. package/es/commands/check/index.d.ts +8 -2
  6. package/es/commands/check/index.js +45 -5
  7. package/es/commands/create/index.d.ts +2 -0
  8. package/es/commands/create/index.js +28 -3
  9. package/es/commands/create/scaffold.d.ts +2 -0
  10. package/es/commands/create/scaffold.js +10 -6
  11. package/es/commands/dev/index.d.ts +1 -1
  12. package/es/commands/dev/index.js +6 -2
  13. package/es/commands/doctor/index.d.ts +12 -0
  14. package/es/commands/doctor/index.js +217 -7
  15. package/es/commands/guide/index.d.ts +29 -0
  16. package/es/commands/guide/index.js +120 -0
  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 +45 -0
  22. package/es/commands/skill/index.js +145 -0
  23. package/es/core/config.d.ts +63 -19
  24. package/es/core/config.js +108 -32
  25. package/es/core/prepare.js +3 -5
  26. package/es/core/project-check.d.ts +15 -0
  27. package/es/core/project-check.js +26 -0
  28. package/es/core/sandbox.d.ts +17 -0
  29. package/es/core/sandbox.js +182 -0
  30. package/es/core/templates.d.ts +25 -0
  31. package/es/core/templates.js +41 -0
  32. package/es/dev/grading.d.ts +14 -7
  33. package/es/dev/grading.js +27 -13
  34. package/es/dev/host-page.d.ts +1 -1
  35. package/es/dev/host-page.js +33 -33
  36. package/es/dev/mock-api.d.ts +20 -4
  37. package/es/dev/mock-api.js +70 -9
  38. package/es/dev/server.d.ts +9 -1
  39. package/es/dev/server.js +101 -25
  40. package/es/rules/check.js +126 -4
  41. package/es/rules/index.d.ts +1 -1
  42. package/es/rules/index.js +1 -1
  43. package/es/rules/manifest.d.ts +23 -9
  44. package/es/rules/manifest.js +60 -35
  45. package/es/rules/node.js +3 -1
  46. package/es/rules/semver.d.ts +5 -0
  47. package/es/rules/semver.js +32 -0
  48. package/es/rules/types.d.ts +29 -6
  49. package/es/rules.json.js +1 -1
  50. package/es/version.d.ts +2 -1
  51. package/es/version.js +5 -1
  52. package/guides/content-development.md +294 -0
  53. package/package.json +4 -2
  54. package/rules.json +113 -5
  55. package/skills/_shared/always.md +9 -0
  56. package/skills/elice-content-check/SKILL.md +22 -0
  57. package/skills/elice-content-create/SKILL.md +21 -0
  58. package/skills/elice-content-migrate/SKILL.md +21 -0
  59. package/skills/elice-content-publish/SKILL.md +22 -0
  60. package/templates/_shared/lib/cdk-mock.d.ts +21 -3
  61. package/templates/_shared/lib/cdk-mock.js +239 -80
  62. package/templates/_shared/lib/cdk.js +2 -2
  63. package/templates/_shared/lib/elice-content.css +206 -0
  64. package/templates/_shared/lib/elice-content.d.ts +112 -5
  65. package/templates/_shared/lib/elice-content.js +660 -62
  66. package/templates/blank/README.md +14 -5
  67. package/templates/blank/commentary.txt +2 -0
  68. package/templates/blank/completion.html +15 -0
  69. package/templates/blank/elice.config.json +3 -5
  70. package/templates/blank/gitignore +1 -0
  71. package/templates/blank/screens/completion.js +7 -0
  72. package/templates/blank/screens/edit.js +3 -0
  73. package/templates/blank/template.json +6 -0
  74. package/templates/quiz/README.md +37 -30
  75. package/templates/quiz/commentary.txt +2 -0
  76. package/templates/quiz/content.json +17 -63
  77. package/templates/quiz/core/behaviors.d.ts +8 -3
  78. package/templates/quiz/core/behaviors.js +15 -2
  79. package/templates/quiz/core/model.d.ts +27 -1
  80. package/templates/quiz/core/model.js +199 -4
  81. package/templates/quiz/elice.config.json +1 -6
  82. package/templates/quiz/gitignore +1 -0
  83. package/templates/quiz/grading.json +1 -10
  84. package/templates/quiz/screens/edit.js +106 -32
  85. package/templates/quiz/screens/learn.js +13 -9
  86. package/templates/quiz/styles.css +84 -24
  87. package/templates/quiz/template.json +6 -0
  88. package/templates/quiz/ui/templates/edit.d.ts +2 -1
  89. package/templates/quiz/ui/templates/edit.js +16 -13
  90. package/templates/quiz/ui/templates/group.js +29 -8
  91. package/templates/quiz/ui/templates/question.js +3 -3
  92. package/templates/quiz/ui/texts.js +53 -29
@@ -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), 없으면 프로젝트의 grading.json({ type: pattern | rubric })과
6
+ * 완료 정책으로 로컬 채점. pattern 답은 정규식 하나, 답 문자열 전체 일치
7
+ * - 완료 정책: material.completionPolicy · completionPolicies와 saveCompletionPolicy를 흉내 낸다. 지원하는 정책은
8
+ * metadata completionPolicies(elice.config.json, 없으면 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';
56
+ const SETTINGS_SAVED_MESSAGE_TYPE = 'settings-saved';
48
57
  /** 템플릿의 metadata.json 진입 파일 (elice.config.json `screens`가 있으면 그것) */
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] grading.json 대신 직접 지정 (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,48 @@ 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
+ this.#grading = normalizeGradingSettings(this.#options.grading) ?? local.grading;
306
+ const policies = this.#options.completionPolicies ?? local.policies;
307
+ this.#policies = policies;
308
+ // 이 브라우저에 저장한 값은 지원하는 정책 안에 있을 때만. null이면 채점 설정이 있으면 on_graded,
309
+ // 없으면 on_submit (#effectivePolicy)
310
+ const stored = this.#store.get('completionPolicy', null);
311
+ this.#policy =
312
+ this.#options.completionPolicy ??
313
+ (POLICIES.includes(stored) && (!policies || policies.includes(stored)) ? stored : null) ??
314
+ local.policy ??
315
+ policies?.[0] ??
316
+ null;
317
+ this.#entries = DEFAULT_ENTRIES;
250
318
 
251
319
  this.#isDraft = isDraft;
252
320
  this.#isSessionExpired = false;
253
321
  this.#draftSubmissions = [];
254
322
  this.#viewer = viewer;
255
- this.#scope = params.edit === '1' ? 'edit' : 'learn';
323
+ this.#scope = editScope ? 'edit' : 'learn';
256
324
  // 실제 SDK와 같은 규칙: edit scope면 edit, 교육자이고 교육자 진입 파일이 있으면 instructor, 그 밖은 learn.
257
325
  // draft는 fragment가 화면을 알려 준다 (#edit=1이면 edit, 아니면 learn)
258
326
  this.#screen =
259
327
  this.#scope === 'edit'
260
- ? 'edit'
328
+ ? completionScreen
329
+ ? 'completionPolicy'
330
+ : 'edit'
261
331
  : !isDraft && viewer === 'instructor' && this.#entries.instructor
262
332
  ? 'instructor'
263
333
  : 'learn';
@@ -274,7 +344,7 @@ export class MockEliceCDK {
274
344
  this.initialized = true;
275
345
  // "들어오면 완료": 학생이 처음 열면 서버가 100점으로 기록한다
276
346
  if (
277
- this.#grading?.type === 'on_access' &&
347
+ this.#effectivePolicy() === 'on_access' &&
278
348
  viewer === 'student' &&
279
349
  !isDraft &&
280
350
  this.#store.get('result', null) === null
@@ -285,10 +355,13 @@ export class MockEliceCDK {
285
355
  completedAt: new Date().toISOString(),
286
356
  });
287
357
  if (this.#scenario === 'session_expired') {
288
- setTimeout(() => {
289
- this.#isSessionExpired = true;
290
- this.#options.onSessionExpired?.();
291
- }, 0);
358
+ setTimeout(
359
+ () => {
360
+ this.#isSessionExpired = true;
361
+ this.#options.onSessionExpired?.();
362
+ },
363
+ 0
364
+ );
292
365
  }
293
366
  return this;
294
367
  }
@@ -312,7 +385,7 @@ export class MockEliceCDK {
312
385
  throw new EliceCDKError(ErrorCode.InvalidInput, 'Answer is over 64KB.');
313
386
  await this.#delay();
314
387
 
315
- const res = gradeLocally(this.#grading, answer);
388
+ const res = gradeLocally(this.#effectiveGrading(), answer, this.#effectivePolicy());
316
389
  if (this.#isDraft) this.#draftSubmissions.unshift(this.#submission(answer, res, 'preview'));
317
390
  else if (this.#viewer === 'student') this.#record(res, answer);
318
391
  return res;
@@ -322,36 +395,92 @@ export class MockEliceCDK {
322
395
  this.#assertReady();
323
396
  await this.#delay();
324
397
  const { offset = 0, limit = 20 } = options;
325
- const submissions = this.#isDraft
326
- ? this.#draftSubmissions
327
- : this.#store.get('submissions', []);
398
+ const submissions = this.#isDraft ? this.#draftSubmissions : this.#store.get('submissions', []);
328
399
  return submissions.slice(offset, offset + limit);
329
400
  }
330
401
 
331
402
  /**
332
- * 설정 화면(screen edit)에서만. 실제 SDK처럼 편집 페이지(부모 창)에 postMessage로 넘기고,
333
- * mock은 브라우저에도 남겨 다른 화면의 `material.settings`로 보이게 한다.
403
+ * 완료 정책 화면(screen completionPolicy)에서만. 실제 SDK처럼 지금 버전의 완료 정책을 바꾸고(mock은 이 브라우저에만)
404
+ * 결과를 편집 페이지에 `settings-saved`로 알린다. 토큰 없는 draft(#completionPolicy=1)는 draft_not_saved,
405
+ * 채점 설정 없는 on_graded는 서버처럼 MATERIAL_GRADING_REQUIRED(request_failed의 cause)로 거절
406
+ * @param {'on_access' | 'on_submit' | 'on_graded'} policy
407
+ */
408
+ async saveCompletionPolicy(policy) {
409
+ this.#assertReady();
410
+ this.#assertScreen('completionPolicy');
411
+ await this.#delay();
412
+ try {
413
+ if (this.#isDraft)
414
+ throw new EliceCDKError(
415
+ ErrorCode.DraftNotSaved,
416
+ 'The completion policy of an unsaved upload cannot be saved (mock).'
417
+ );
418
+ if (!POLICIES.includes(policy))
419
+ throw new EliceCDKError(ErrorCode.InvalidInput, `Unknown completion policy: ${policy}`);
420
+ if (policy === 'on_graded' && !this.#effectiveGrading())
421
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Grading is required (mock).', {
422
+ cause: { code: 'MATERIAL_GRADING_REQUIRED' },
423
+ });
424
+ if (this.#scenario === 'material_changed')
425
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Material changed (mock).', {
426
+ cause: { code: 'MATERIAL_CHANGED' },
427
+ });
428
+ this.#policy = policy;
429
+ this.#store.set('completionPolicy', policy);
430
+ this.#postSettingsSaved({ status: 'saved' });
431
+ } catch (err) {
432
+ const code = err.cause?.cause?.code ?? err.code;
433
+ this.#postSettingsSaved({ status: 'failed', code });
434
+ throw err;
435
+ }
436
+ }
437
+
438
+ /**
439
+ * 편집 화면(screen edit)에서만. 실제 SDK처럼 저장하고(mock은 브라우저에 남겨 다른 화면의 `material.settings`로 보임)
440
+ * 결과를 편집 페이지(부모 창)에 `settings-saved`로 알린다. 토큰 없는 draft(#edit=1)는 `draft_not_saved`로 거절.
441
+ * 시나리오 ?mock=material_changed면 다른 사람이 먼저 저장한 것처럼 실패한다 (실제 SDK: request_failed, 서버 코드는 cause)
334
442
  */
335
- saveSettings(settings) {
443
+ async saveSettings(settings) {
336
444
  this.#assertReady();
337
445
  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
- );
446
+ await this.#delay();
447
+ try {
448
+ if (this.#isDraft)
449
+ throw new EliceCDKError(
450
+ ErrorCode.DraftNotSaved,
451
+ 'Settings of an unsaved upload cannot be saved (mock).'
452
+ );
453
+ if (this.#scenario === 'material_changed')
454
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Material changed (mock).', {
455
+ cause: { code: 'MATERIAL_CHANGED' },
456
+ });
457
+ if (this.#scenario === 'request_failed')
458
+ throw new EliceCDKError(ErrorCode.RequestFailed, 'Network error (mock).');
459
+ this.#store.set('settings', settings);
460
+ this.#postSettingsSaved({ status: 'saved' });
461
+ } catch (err) {
462
+ const code = err.cause?.cause?.code ?? err.code;
463
+ this.#postSettingsSaved({ status: 'failed', code });
464
+ throw err;
352
465
  }
353
466
  }
354
467
 
468
+ #postSettingsSaved(payload) {
469
+ const parent = globalThis.parent;
470
+ if (!parent || parent === globalThis || typeof parent.postMessage !== 'function') return;
471
+ // sandbox(출처 null)라 부모 출처를 알 수 없어 실제 SDK도 '*'로 보낸다. 편집 페이지가 event.source로 확인
472
+ // ecdk-ignore-next-line sec.postmessage-wildcard
473
+ parent.postMessage(
474
+ {
475
+ source: MESSAGE_SOURCE,
476
+ type: SETTINGS_SAVED_MESSAGE_TYPE,
477
+ materialId: this.#metadata.materialId,
478
+ payload,
479
+ },
480
+ '*'
481
+ );
482
+ }
483
+
355
484
  /** 실제 SDK: 토큰 자동 갱신을 멈춘다. mock은 갱신이 없어 아무것도 하지 않는다 */
356
485
  dispose() {}
357
486
 
@@ -360,9 +489,20 @@ export class MockEliceCDK {
360
489
  this.#store.set('settings', {});
361
490
  this.#store.set('submissions', []);
362
491
  this.#store.set('result', null);
492
+ this.#store.set('completionPolicy', null);
363
493
  this.#draftSubmissions = [];
364
494
  }
365
495
 
496
+ /** 저장된 채점 설정(편집 화면), 없으면 로컬(grading.json · options.grading) */
497
+ #effectiveGrading() {
498
+ return normalizeGradingSettings(this.#store.get('settings', {}).grading) ?? this.#grading;
499
+ }
500
+
501
+ /** 정해진 완료 정책, 없으면 채점 설정이 있으면 on_graded · 없으면 on_submit */
502
+ #effectivePolicy() {
503
+ return this.#policy ?? (this.#effectiveGrading() ? 'on_graded' : 'on_submit');
504
+ }
505
+
366
506
  #assertReady() {
367
507
  if (!this.initialized) throw new EliceCDKError(ErrorCode.NotInitialized, 'Call init() first.');
368
508
  if (this.#isSessionExpired)
@@ -373,7 +513,7 @@ export class MockEliceCDK {
373
513
  if (!screens.includes(this.#screen))
374
514
  throw new EliceCDKError(
375
515
  ErrorCode.ScreenNotSupported,
376
- `This call is only available on the ${screens.join(' or ')} screen.`,
516
+ `This call is only available on the ${screens.join(' or ')} screen.`
377
517
  );
378
518
  }
379
519
 
@@ -396,7 +536,8 @@ export class MockEliceCDK {
396
536
  this.#store.set('submissions', submissions);
397
537
  const prev = this.#store.get('result', null);
398
538
  const score = res.score ?? prev?.score ?? null;
399
- const completed = res.score === 100 || this.#grading?.type === 'none';
539
+ // 완료는 통과(isCorrect)로: on_submit · pattern 100점 · rubric 흉내 점수
540
+ const completed = res.isCorrect === true;
400
541
  this.#store.set('result', {
401
542
  score,
402
543
  submitCount: (prev?.submitCount ?? 0) + 1,
@@ -404,22 +545,40 @@ export class MockEliceCDK {
404
545
  });
405
546
  }
406
547
 
407
- async #loadConfig() {
548
+ /**
549
+ * 로컬 채점 설정 · 완료 정책. ecdk dev의 콘텐츠 주소를 직접 열면 dev가 주는 값을, 프로젝트 폴더를 그대로 열면
550
+ * grading.json · .ecdk/completion.json과 completionPolicies(elice.config.json, 없으면 metadata.json)를 읽는다
551
+ * (grading.json · .ecdk는 zip에서 빠짐, 로컬 채점용으로 일부러 읽음). 완료 정책은 .ecdk(목록 안일 때) > 첫 값
552
+ * @returns {Promise<{ grading: object | null, policy: string | null, policies: string[] | null }>}
553
+ */
554
+ async #loadLocal() {
408
555
  const loadJson =
409
- this.#options.loadJson ?? ((url) => fetch(url).then((r) => (r.ok ? r.json() : null)));
410
- // ecdk dev의 콘텐츠 주소를 직접 열었을 때: 설정 파일은 zip처럼 빠져 있으니 dev가 주는 로컬 채점 설정을 쓴다
556
+ this.#options.loadJson ?? (url => fetch(url).then(r => (r.ok ? r.json() : null)));
557
+ const listOf = v => (Array.isArray(v) && v.length > 0 && v.every(p => POLICIES.includes(p)) ? v : null);
411
558
  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;
559
+ if (typeof devGrading === 'string') {
560
+ const dev = await loadJson(devGrading).catch(() => null);
561
+ return {
562
+ grading: normalizeGradingSettings(dev?.grading),
563
+ policy: POLICIES.includes(dev?.completion_policy) ? dev.completion_policy : null,
564
+ policies: listOf(dev?.completion_policies),
565
+ };
566
+ }
567
+ if (this.#options.grading) return { grading: null, policy: null, policies: null };
419
568
  // ecdk-ignore-next-line project.answer-import
420
569
  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] };
570
+ const local = await loadJson('.ecdk/completion.json').catch(() => null);
571
+ const manifest =
572
+ // ecdk-ignore-next-line project.answer-import
573
+ (await loadJson('elice.config.json').catch(() => null)) ??
574
+ (await loadJson('metadata.json').catch(() => null));
575
+ const policies = listOf(manifest?.completionPolicies);
576
+ const saved = local?.completion_policy;
577
+ return {
578
+ grading: normalizeGradingSettings(data),
579
+ policy: policies?.includes(saved) ? saved : (policies?.[0] ?? null),
580
+ policies,
581
+ };
423
582
  }
424
583
 
425
584
  async #delay() {