@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
@@ -3,24 +3,33 @@
3
3
  *
4
4
  * 화면은 누가 보는지(학생 · 교육자 · 튜터)나 미리보기인지 몰라도 됩니다.
5
5
  * 학생 화면: app.useSubmit({ getAnswer, setAnswer, validate })
6
- * 편집 화면: app.useSave({ getContent, validate })
6
+ * 편집 화면: app.useSave({ getContent, getGrading, validate }) · 채점 방식과 답: app.useGradingBlock() (퀴즈가 아닌 자료)
7
+ * 완료 정책 화면: app.useCompletion() (metadata completionPolicies 안에서 고르고 SDK saveCompletionPolicy로 저장)
8
+ * 여러 단계: app.usePaging({ count, onChange }) (옆 화살표 · n / N, 첫 · 마지막 단계에서 이전 · 다음 자료)
7
9
  * 읽기 전용 잠금, 답 복원, 결과·오류 안내, 저장 문구, 로컬 mock 표시는 키트가 합니다.
8
10
  *
9
11
  * 화면(screens/*.js)은 이 키트만 부릅니다. 키트가 SDK로 인증 · 화면 확인 · 내용 불러오기 ·
10
12
  * 제출 · 저장 · 오류 안내를 처리합니다. SDK는 둘 중 하나를 자동으로 고릅니다.
11
13
  *
12
14
  * real lib/cdk.js (@eliceio/cdk 1.x) 플랫폼에서 열 때 (#token=, 편집기 #preview=1 · #edit=1)
15
+ * 편집 화면은 edit 토큰으로 열려 '저장'이 서버에 바로 저장
13
16
  * mock lib/cdk-mock.js (같은 인터페이스) 그 밖 (로컬): 로컬 채점, 화면 사이 저장 공유
14
17
  *
15
18
  * 바꾸기: 주소에 ?sdk=mock 또는 ?sdk=real, 또는 start({ screen, sdk: 'mock' })
16
- * 로컬에서 보는 사람 바꾸기 (mock): #viewer=tutor (student · instructor · tutor), 미리보기: #preview=1
19
+ * 로컬에서 보는 사람 바꾸기 (mock): #viewer=tutor (student · instructor · tutor), 미리보기: #preview=1,
20
+ * 편집 화면: #scope=edit (저장되는 편집 화면) · #edit=1 (저장 전 업로드라 저장 안 됨)
17
21
  *
18
22
  * import { start } from '../lib/elice-content.js';
19
23
  * const app = await start({ screen: 'learn' });
20
- * app.content // 편집 화면(CMS)이 저장한 내용, 없으면 content.json
24
+ * if (!app.hasContent) root.replaceChildren(app.emptyState()) // 편집 화면에서 아직 저장하지 않음
25
+ * app.content // 편집 화면(CMS)이 저장한 내용 (settings, 없으면 {})
21
26
  * await app.submit(answer)
22
27
  *
23
- * 정답은 콘텐츠에 넣지 않습니다. 채점은 서버가 편집 화면의 채점 설정으로 합니다.
28
+ * 정답은 콘텐츠(zip)에 넣지 않습니다. 채점은 서버가 채점 설정(settings.grading)으로 합니다 (ADR 0009).
29
+ * 채점 설정 { type: pattern | rubric, answer_key | rubric }은 편집 화면이 edit 토큰으로 저장하고, 서버는 학생에게
30
+ * settings.grading을 내려주지 않습니다. 완료 정책(on_access · on_submit · on_graded)은 settings가 아니라
31
+ * material_version.completion_policy입니다: 자료가 지원하는 정책은 metadata completionPolicies(서버가 첫 값으로 정함)이고,
32
+ * 완료 정책 화면이 그 안에서 SDK saveCompletionPolicy로 바꿉니다 (키트 app.completion.get() · set()).
24
33
  */
25
34
 
26
35
  /**
@@ -29,10 +38,11 @@
29
38
  * 파일 하나로 두 화면을 같이 쓸 수도 있다. 교육자 화면은 교육자만 본다.
30
39
  */
31
40
  const SCREEN_ALLOWED = {
32
- learn: (sdk) => sdk.screen === 'learn' || sdk.screen === 'instructor',
33
- instructor: (sdk) =>
41
+ learn: sdk => sdk.screen === 'learn' || sdk.screen === 'instructor',
42
+ instructor: sdk =>
34
43
  (sdk.screen === 'learn' || sdk.screen === 'instructor') && sdk.viewer === 'instructor',
35
- edit: (sdk) => sdk.screen === 'edit',
44
+ edit: sdk => sdk.screen === 'edit',
45
+ completionPolicy: sdk => sdk.screen === 'completionPolicy',
36
46
  };
37
47
 
38
48
  const MESSAGES = {
@@ -42,10 +52,18 @@ const MESSAGES = {
42
52
  rate_limited: '제출이 너무 잦습니다. 잠시 뒤 다시 시도해 주세요.',
43
53
  invalid_input: '답이 너무 크거나 형식이 올바르지 않습니다.',
44
54
  content_not_ready: '아직 저장된 자료가 없습니다.',
55
+ // 키트만의 문구: 편집 화면이 아직 내용을 저장하지 않음 (기본 내용 파일은 없음)
56
+ content_empty: '아직 내용이 없습니다. 편집 화면에서 내용을 만들어 저장하면 여기에 보입니다.',
45
57
  external_service_error: '채점하지 못했어요. 제출이 저장되지 않았으니 다시 제출해 주세요.',
46
58
  screen_not_supported: '이 화면에서는 할 수 없는 일입니다.',
47
59
  navigation_timeout: '수업 페이지 정보를 받지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
48
60
  permission_denied: '권한이 없습니다.',
61
+ draft_not_saved: '업로드한 자료를 먼저 저장해야 내용을 편집해 저장할 수 있어요.',
62
+ // 서버 코드: 채점 설정(settings.grading) 없이 채점해 완료(on_graded)를 고름
63
+ material_grading_required:
64
+ '채점 방식과 답이 아직 없어 채점해 통과하면 완료로 바꿀 수 없어요. 내용 편집에서 답을 먼저 저장해 주세요.',
65
+ // 서버 코드 (SDK request_failed의 cause): 편집하는 사이 다른 곳에서 자료를 저장함
66
+ material_changed: '그 사이 다른 곳에서 자료가 저장됐어요. 새로고침한 뒤 다시 편집해 주세요.',
49
67
  not_initialized: '아직 준비되지 않았습니다.',
50
68
  request_failed: '서버와 연결하지 못했습니다. 잠시 뒤 다시 시도해 주세요.',
51
69
  // 키트만의 코드: 자료 주소인데 접속 토큰이 없음 (새로고침 · 다른 HTML로 이동하면 SDK가 지운 토큰이 남지 않는다)
@@ -69,20 +87,84 @@ export class ContentError extends Error {
69
87
  /** SDK 오류를 화면이 그대로 보여 줄 수 있는 한국어 메시지로 */
70
88
  function toContentError(err) {
71
89
  if (err instanceof ContentError) return err;
90
+ // 서버 오류 코드는 SDK 오류(request_failed)의 cause.cause.code에 있다 (예: 409 MATERIAL_CHANGED)
91
+ const serverCode = err?.cause?.cause?.code;
92
+ if (serverCode === 'MATERIAL_CHANGED')
93
+ return new ContentError('material_changed', MESSAGES.material_changed, err);
94
+ if (serverCode === 'MATERIAL_GRADING_REQUIRED')
95
+ return new ContentError('material_grading_required', MESSAGES.material_grading_required, err);
72
96
  const code = typeof err?.code === 'string' ? err.code : 'request_failed';
73
97
  return new ContentError(code, MESSAGES[code] ?? MESSAGES.request_failed, err);
74
98
  }
75
99
 
76
100
  const MATERIAL_PATH = /\/materials\/[0-9a-f-]{36}\//i;
77
101
 
102
+ /**
103
+ * 저장된 채점 설정을 서버 모양(2026-11-11 결정)으로: `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }`.
104
+ * 실제 SDK는 응답 키를 camelCase로 바꿔 answer_key가 answerKey로 온다 (보낼 때는 snake_case로, progress G129).
105
+ * 채점 방식이 아닌 값(옛 on_access · on_submit 등)이면 null
106
+ */
107
+ export function normalizeGrading(grading) {
108
+ if (!grading || typeof grading !== 'object') return null;
109
+ if (grading.type === 'pattern') {
110
+ const answerKey = grading.answer_key ?? grading.answerKey;
111
+ return { type: 'pattern', ...(typeof answerKey === 'string' ? { answer_key: answerKey } : {}) };
112
+ }
113
+ if (grading.type === 'rubric')
114
+ return { type: 'rubric', ...(typeof grading.rubric === 'string' ? { rubric: grading.rubric } : {}) };
115
+ return null;
116
+ }
117
+
118
+ /** 완료 정책 값 (서버 material_version.completion_policy) */
119
+ const POLICY_VALUES = Object.freeze(['on_access', 'on_submit', 'on_graded']);
120
+
121
+ /**
122
+ * 완료 정책 읽기 · 바꾸기. 지금 값은 SDK material.completionPolicy, 지원하는 정책은 material.completionPolicies
123
+ * (metadata completionPolicies. 서버가 아직 돌려주지 않으면 null, G132), 저장은 SDK saveCompletionPolicy
124
+ * (PATCH completion_policy, 완료 정책 화면에서만). 값 이름은 서버와 같은 completion_policy
125
+ * @returns {{ readonly policies: string[] | null, get(): Promise<{ completion_policy: string | null, policies: string[] | null }>, set(policy: string): Promise<void> }}
126
+ */
127
+ function completionApi(sdk) {
128
+ const listed = () => {
129
+ const policies = sdk.material?.completionPolicies;
130
+ return Array.isArray(policies) && policies.length > 0 ? policies : null;
131
+ };
132
+ return {
133
+ get policies() {
134
+ return listed();
135
+ },
136
+ async get() {
137
+ return { completion_policy: sdk.material?.completionPolicy ?? null, policies: listed() };
138
+ },
139
+ async set(policy) {
140
+ const policies = listed() ?? POLICY_VALUES;
141
+ if (!policies.includes(policy))
142
+ throw new ContentError(
143
+ 'invalid_input',
144
+ `이 자료가 지원하지 않는 완료 정책입니다: ${policy} (가능: ${policies.join(', ')})`
145
+ );
146
+ try {
147
+ await sdk.saveCompletionPolicy(policy);
148
+ } catch (err) {
149
+ throw toContentError(err);
150
+ }
151
+ },
152
+ };
153
+ }
154
+
78
155
  /** 로컬 mock에서 화면별 기본 fragment (보는 사람 · 설정 화면) */
79
- const LOCAL_MOCK_HASH = { learn: '', instructor: 'viewer=instructor', edit: 'edit=1' };
156
+ const LOCAL_MOCK_HASH = {
157
+ learn: '',
158
+ instructor: 'viewer=instructor',
159
+ edit: 'scope=edit',
160
+ completionPolicy: 'scope=edit&screen=completionPolicy',
161
+ };
80
162
 
81
- /** 토큰 없는 draft: 편집기 미리보기 · 설정 화면 */
82
- const DRAFT_HASH = /(?:^#|&)(?:preview|edit)=1/;
83
- const LAUNCH_HASH = /(?:^#|&)(?:token|preview|edit)=/;
163
+ /** 토큰 없는 draft: 편집기 미리보기 · 편집 화면 · 완료 정책 화면 */
164
+ const DRAFT_HASH = /(?:^#|&)(?:preview|edit|completionPolicy)=1/;
165
+ const LAUNCH_HASH = /(?:^#|&)(?:token|preview|edit|completionPolicy)=/;
84
166
 
85
- const isLoopback = (h) => h === 'localhost' || h === '127.0.0.1' || h === '[::1]';
167
+ const isLoopback = h => h === 'localhost' || h === '127.0.0.1' || h === '[::1]';
86
168
 
87
169
  /**
88
170
  * 어떤 SDK를 쓸지. ?sdk=가 있으면 그대로, 플랫폼 주소(토큰 · 편집기 미리보기)면 real, 그 밖은 mock.
@@ -103,7 +185,8 @@ export function pickSdk({ hash, pathname, search, hostname = '' }) {
103
185
 
104
186
  /** mock: 주소에 보는 사람 · 미리보기 · 설정 화면이 없으면 화면에 맞게 */
105
187
  function mockLaunch(hash, screen) {
106
- if (/(?:^#|&)(?:viewer|preview|edit)=/.test(hash)) return { hash, pathname: '/', local: true };
188
+ if (/(?:^#|&)(?:viewer|preview|edit|completionPolicy|scope)=/.test(hash))
189
+ return { hash, pathname: '/', local: true };
107
190
  const parts = [LOCAL_MOCK_HASH[screen], hash.replace(/^#/, '')].filter(Boolean);
108
191
  return { hash: parts.length ? `#${parts.join('&')}` : '', pathname: '/', local: true };
109
192
  }
@@ -131,9 +214,7 @@ async function loadRealSdk() {
131
214
  script.src = new URL('./cdk.js', import.meta.url).href;
132
215
  script.onload = resolve;
133
216
  script.onerror = () =>
134
- reject(
135
- new ContentError('request_failed', 'SDK 파일(lib/cdk.js)을 불러오지 못했습니다.'),
136
- );
217
+ reject(new ContentError('request_failed', 'SDK 파일(lib/cdk.js)을 불러오지 못했습니다.'));
137
218
  document.head.append(script);
138
219
  });
139
220
  return globalThis.elice.EliceCDK;
@@ -157,7 +238,12 @@ export function resolveLaunch(hash, pathname, screen) {
157
238
  return { hash, pathname: local ? LOCAL_MATERIAL_PATH : pathname, local };
158
239
  }
159
240
  return {
160
- hash: screen === 'edit' ? '#edit=1' : '#preview=1',
241
+ hash:
242
+ screen === 'edit'
243
+ ? '#edit=1'
244
+ : screen === 'completionPolicy'
245
+ ? '#completionPolicy=1'
246
+ : '#preview=1',
161
247
  pathname: LOCAL_MATERIAL_PATH,
162
248
  local: true,
163
249
  };
@@ -165,12 +251,11 @@ export function resolveLaunch(hash, pathname, screen) {
165
251
 
166
252
  /**
167
253
  * @typedef {object} StartOptions
168
- * @property {'learn' | 'instructor' | 'edit'} screen 이 HTML이 어떤 화면인지
169
- * @property {string} [defaults] 저장된 내용이 없을 때 쓸 내용 파일 (기본 'content.json')
254
+ * @property {'learn' | 'instructor' | 'edit' | 'completionPolicy'} screen 이 HTML이 어떤 화면인지
170
255
  * @property {(error: ContentError) => void} [onError] 화면 밖 오류(세션 만료 등)를 받을 함수. 기본은 상단 알림
171
256
  * @property {'real' | 'mock' | object} [sdk] SDK 고르기 (기본: pickSdk). 객체면 그대로 씀 (테스트)
172
257
  * @property {object} [mock] mock 옵션 (scenario, grading, settings, delayMs)
173
- * @property {(url: string) => Promise<unknown>} [loadJson] 테스트용
258
+ * @property {(url: string) => Promise<unknown>} [loadJson] 테스트용 (mock이 읽는 로컬 파일)
174
259
  * @property {string} [hash] 테스트용: location.hash 대신
175
260
  * @property {string} [pathname] 테스트용: location.pathname 대신
176
261
  * @property {string} [search] 테스트용: location.search 대신
@@ -183,7 +268,7 @@ export function resolveLaunch(hash, pathname, screen) {
183
268
  * @param {StartOptions} options
184
269
  */
185
270
  export async function start(options) {
186
- const { screen, defaults = 'content.json' } = options;
271
+ const { screen } = options;
187
272
  if (!SCREEN_ALLOWED[screen]) throw new Error(`알 수 없는 화면: ${screen}`);
188
273
  const notify = options.onError ?? showBanner;
189
274
 
@@ -214,7 +299,7 @@ export async function start(options) {
214
299
  } else sdk = new (await loadRealSdk())({ onSessionExpired, ...devApi() });
215
300
  if (kind === 'mock' && typeof console !== 'undefined')
216
301
  console.info(
217
- '[elice-content] mock SDK 사용 중 (실제 서버에 저장되지 않음). 실제 SDK: ?sdk=real',
302
+ '[elice-content] mock SDK 사용 중 (실제 서버에 저장되지 않음). 실제 SDK: ?sdk=real'
218
303
  );
219
304
  } catch (err) {
220
305
  const e = toContentError(err);
@@ -237,16 +322,19 @@ export async function start(options) {
237
322
  if (!SCREEN_ALLOWED[screen](sdk)) {
238
323
  const e = new ContentError(
239
324
  'screen_not_supported',
240
- `이 파일은 ${screen} 화면인데 ${sdk.screen} 화면(보는 사람 ${viewer})으로 열렸습니다. metadata.json의 진입 파일을 확인해 주세요.`,
325
+ `이 파일은 ${screen} 화면인데 ${sdk.screen} 화면(보는 사람 ${viewer})으로 열렸습니다. metadata.json의 진입 파일을 확인해 주세요.`
241
326
  );
242
327
  notify(e);
243
328
  throw e;
244
329
  }
245
330
 
246
- const saved = sdk.material?.settings;
247
- const loadJson = options.loadJson ?? ((url) => fetch(url).then((r) => (r.ok ? r.json() : {})));
248
- let content =
249
- saved && Object.keys(saved).length > 0 ? saved : await loadJson(defaults).catch(() => ({}));
331
+ // 저장된 settings에서 채점 설정(grading, edit 범위에만 옴)을 떼어 둔다: 화면 내용(content)은 grading 없이.
332
+ // 내용은 편집 화면이 저장한 settings뿐이다 (기본 내용 파일은 없음, ADR 0011). 아직 없으면 {}이고 hasContent가 false
333
+ const { grading: rawGrading = null, ...saved } = sdk.material?.settings ?? {};
334
+ let content = saved;
335
+ let grading = normalizeGrading(rawGrading);
336
+ /** 다음 저장의 바탕: 서버에 저장된 settings 그대로 */
337
+ let savedSettings = sdk.material?.settings ?? {};
250
338
 
251
339
  const readOnly = viewer === 'tutor';
252
340
  const app = {
@@ -274,10 +362,25 @@ export async function start(options) {
274
362
  get records() {
275
363
  return viewer === 'student' && !app.isDraft && kind !== 'mock';
276
364
  },
277
- /** 편집 화면(CMS)이 저장한 내용. 학생에게도 공개되므로 정답을 넣지 않는다 */
365
+ /** 편집 화면(CMS)이 저장한 내용. 학생에게도 공개되므로 정답을 넣지 않는다. 아직 저장하지 않았으면 {} */
278
366
  get content() {
279
367
  return content;
280
368
  },
369
+ /** 편집 화면이 내용을 저장했는지. false면 학생 · 교육자 화면은 emptyState()를 보여 준다 */
370
+ get hasContent() {
371
+ return Object.keys(content).length > 0;
372
+ },
373
+ /** 내용이 없을 때 보여 줄 안내 ("아직 내용이 없습니다 …"). 학생 · 교육자 화면에서 app.hasContent가 false일 때 */
374
+ emptyState() {
375
+ return h('p', { className: 'ec-empty', role: 'status', textContent: MESSAGES.content_empty });
376
+ },
377
+ /**
378
+ * 저장된 채점 설정 `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }` 또는 null.
379
+ * edit 범위(편집 · 완료 정책 화면)에서만 오고, 학생 · 튜터 · 교육자 화면에는 서버가 내려주지 않는다
380
+ */
381
+ get grading() {
382
+ return grading;
383
+ },
281
384
 
282
385
  /** 답 제출 → 서버 채점 결과 { isCorrect, score } (점수 없는 채점이면 둘 다 null). 보통은 useSubmit을 쓴다 */
283
386
  async submit(answer) {
@@ -306,18 +409,35 @@ export async function start(options) {
306
409
  }
307
410
  },
308
411
 
309
- /** 내용 저장 (편집 화면): SDK saveSettings로 편집 페이지에 넘긴다. 보통은 useSave를 쓴다 */
310
- async saveContent(next) {
412
+ /**
413
+ * 내용 저장 (편집 화면): SDK saveSettings가 edit 토큰으로 서버에 바로 저장한다. 보통은 useSave를 쓴다.
414
+ * nextGrading(채점 설정 `{ type, answer_key | rubric }`)을 주면 settings.grading으로 같이 저장하고,
415
+ * 주지 않으면 저장된 채점 설정을 그대로 둔다
416
+ * @param {Record<string, unknown>} next
417
+ * @param {{ type: 'pattern' | 'rubric', answer_key?: string, rubric?: string }} [nextGrading]
418
+ */
419
+ async saveContent(next, nextGrading) {
311
420
  if (screen !== 'edit')
312
421
  throw new ContentError('screen_not_supported', '내용은 편집 화면에서만 저장합니다.');
313
422
  try {
314
- await sdk.saveSettings(next);
423
+ const g = nextGrading ?? grading;
424
+ const settings = g ? { ...next, grading: g } : next;
425
+ await sdk.saveSettings(settings);
315
426
  content = next;
427
+ grading = g;
428
+ savedSettings = settings;
316
429
  } catch (err) {
317
430
  throw toContentError(err);
318
431
  }
319
432
  },
320
433
 
434
+ /**
435
+ * 완료 정책 (on_access · on_submit · on_graded). settings가 아니라 material_version.completion_policy:
436
+ * policies는 metadata completionPolicies, set은 SDK saveCompletionPolicy (완료 정책 화면에서만).
437
+ * 보통은 완료 정책 화면에서 useCompletion을 쓴다
438
+ */
439
+ completion: completionApi(sdk),
440
+
321
441
  /**
322
442
  * 학생 화면의 제출 영역. 화면은 답을 모으고 채우는 방법만 알려 주면, 보는 사람별 처리는 키트가 한다.
323
443
  * - 튜터링: 화면을 읽기 전용으로 잠그고 학생 답을 채움, 제출 버튼 없음
@@ -336,6 +456,36 @@ export async function start(options) {
336
456
  useSave(opts) {
337
457
  return mountSave(app, opts);
338
458
  },
459
+
460
+ /**
461
+ * 편집 화면의 채점 방식 · 답 블록 (퀴즈가 아닌 자료, ADR 0009). LXP 설정 탭과 같은 문구로 채점 방식(기준 답안 정규식 ·
462
+ * 평가 기준)을 고르고 입력한다. 돌려준 getGrading을 useSave({ getGrading })에 넘기면 내용과 함께 저장된다.
463
+ * 퀴즈처럼 문항 구조가 있는 화면은 이 블록 대신 문항별로 답을 받아 정규식을 만든다
464
+ * @param {GradingBlockOptions} [opts]
465
+ */
466
+ useGradingBlock(opts) {
467
+ return mountGradingBlock(app, opts ?? {});
468
+ },
469
+
470
+ /**
471
+ * 완료 정책 화면 (LXP 설정 탭의 완료 정책 영역, ADR 0009). 정책 라디오 · 저장 버튼 · 변경 표시를 키트가 한다.
472
+ * metadata completionPolicies 안의 정책만 보이고, 저장은 app.completion.set (SDK saveCompletionPolicy).
473
+ * completionPolicies가 하나(고정)인 자료는 이 화면을 두지 않는다
474
+ * @param {CompletionOptions} [opts]
475
+ */
476
+ useCompletion(opts) {
477
+ return mountCompletion(app, opts ?? {});
478
+ },
479
+
480
+ /**
481
+ * 자료 안 여러 단계 이동. 내용 양옆 동그란 화살표 + 안쪽 `n / N` 표시.
482
+ * 첫 단계의 왼쪽 · 마지막 단계의 오른쪽은 LXP 이전 · 다음 수업 자료로 가는 버튼(모양이 다름)이 되고,
483
+ * 그쪽 수업 자료가 없거나 LXP 밖이면 숨긴다. LXP 아래 이전 · 다음 막대와 헷갈리지 않게 아래 막대는 만들지 않는다.
484
+ * @param {PagingOptions} opts
485
+ */
486
+ usePaging(opts) {
487
+ return mountPaging(app, opts);
488
+ },
339
489
  };
340
490
  if (options.status !== false) showStatus(app);
341
491
  return app;
@@ -351,16 +501,26 @@ export async function start(options) {
351
501
  * @property {string} [label] 버튼 글자 (기본 '제출')
352
502
  */
353
503
 
504
+ /**
505
+ * @typedef {object} PagingOptions
506
+ * @property {number} count 단계 수 (1 이상)
507
+ * @property {(step: number) => void} onChange 단계가 바뀔 때 (0부터). 시작할 때도 한 번
508
+ * @property {number} [start] 처음 단계 (기본 0)
509
+ * @property {Element} [root] 화살표를 붙일 영역 (기본 #app)
510
+ */
511
+
354
512
  /**
355
513
  * @typedef {object} SaveOptions
356
514
  * @property {() => Record<string, unknown>} getContent 저장할 내용 (학생에게 공개, 정답 넣지 않음)
515
+ * @property {() => object | string | undefined} [getGrading] 같이 저장할 채점 방식 · 답 (settings.grading에 합침, 학생에게 안 감).
516
+ * 문장이면 저장을 막고 보여 줌, undefined면 채점 설정은 그대로 (ADR 0009)
357
517
  * @property {(content: Record<string, unknown>) => true | string} [validate]
358
518
  * @property {Element} [root] 변경을 지켜볼 화면 영역 (기본 #app)
359
519
  * @property {string} [label] 버튼 글자 (기본 '저장')
360
520
  */
361
521
 
362
522
  const h = (tag, props = {}) => Object.assign(document.createElement(tag), props);
363
- const appRoot = (root) => root ?? document.getElementById('app') ?? document.body;
523
+ const appRoot = root => root ?? document.getElementById('app') ?? document.body;
364
524
 
365
525
  /**
366
526
  * 화면 맨 위 안내 한 줄. 로컬 개발용 mock SDK일 때만 (실제 서버에 저장되지 않는다는 것과 보는 사람).
@@ -369,6 +529,7 @@ const appRoot = (root) => root ?? document.getElementById('app') ?? document.bod
369
529
  export function statusText(app) {
370
530
  if (app.sdkKind !== 'mock') return '';
371
531
  if (app.screen === 'edit') return 'mock SDK · 저장 내용은 이 브라우저에만';
532
+ if (app.screen === 'completionPolicy') return 'mock SDK · 완료 정책은 이 브라우저에만';
372
533
  const parts = ['mock SDK · 로컬 채점, 서버에 저장되지 않음'];
373
534
  if (app.viewer === 'tutor')
374
535
  parts.push(`튜터링 · ${app.account?.fullname ?? '학생'}의 화면 (읽기 전용)`);
@@ -390,7 +551,9 @@ function showStatus(app) {
390
551
  function resultText(r) {
391
552
  // 점수 없는 채점(manual · none): 교육자가 매긴 점수는 나중에 결과로 보인다
392
553
  if (r.score === null || r.score === undefined) return '제출했어요.';
393
- return r.isCorrect ? `모두 맞았어요. ${r.score}점` : `${r.score}점이에요. 다시 풀어 볼 수 있어요.`;
554
+ return r.isCorrect
555
+ ? `모두 맞았어요. ${r.score}점`
556
+ : `${r.score}점이에요. 다시 풀어 볼 수 있어요.`;
394
557
  }
395
558
 
396
559
  function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, label = '제출' }) {
@@ -423,7 +586,7 @@ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, labe
423
586
  setAnswer || onResult
424
587
  ? app
425
588
  .lastSubmission()
426
- .then((last) => {
589
+ .then(last => {
427
590
  if (!last) return;
428
591
  if (setAnswer && last.answer !== null && last.answer !== undefined)
429
592
  setAnswer(last.answer);
@@ -457,22 +620,127 @@ function mountSubmit(app, { getAnswer, setAnswer, validate, onResult, root, labe
457
620
  return { element: bar, result, restored };
458
621
  }
459
622
 
460
- function mountSave(app, { getContent, validate, root, label = '저장' }) {
623
+ /** LXP 이전 · 다음 수업 자료가 있는지. 답이 없거나(LXP 밖 · 미리보기 · 시간 초과) 오류면 없음 */
624
+ async function hasLecturePage(app, side) {
625
+ const nav = app.navigation;
626
+ if (!nav) return false;
627
+ try {
628
+ return Boolean(await (side === 'prev' ? nav.getHasPrevious() : nav.getHasNext()));
629
+ } catch {
630
+ return false;
631
+ }
632
+ }
633
+
634
+ function mountPaging(app, { count, onChange, start = 0, root }) {
635
+ const area = appRoot(root);
636
+ const total = Math.max(1, Math.floor(count));
637
+ let step = Math.min(Math.max(0, Math.floor(start)), total - 1);
638
+ const edge = { prev: false, next: false };
639
+ const button = (side) =>
640
+ h('button', { type: 'button', className: `ec-step-nav ${side}` });
641
+ const prev = button('prev');
642
+ const next = button('next');
643
+ const counter = h('p', { className: 'ec-step-count' });
644
+ counter.setAttribute('aria-live', 'polite');
645
+ // 키트 틀(.ec-paging)이 내용 영역을 감싼다: 버튼 · n / N은 틀에, 화면 코드는 내용 영역(기본 #app)에만 그린다.
646
+ // 그래서 화면 코드가 #app을 replaceChildren · innerHTML로 다시 그려도 버튼이 지워지지 않는다
647
+ let frame;
648
+ if (area === document.body || !area.parentNode) {
649
+ // 감쌀 수 없는 영역(body)이면 그 안에 붙인다 (다시 그리면 지워짐)
650
+ frame = area;
651
+ area.append(prev, next, counter);
652
+ } else {
653
+ frame = h('div', { className: 'ec-paging-frame' });
654
+ area.before(frame);
655
+ frame.append(prev, next, area, counter);
656
+ }
657
+ frame.classList.add('ec-paging');
658
+ area.classList.add('ec-step-content');
659
+
660
+ // 단계 안: 동그란 화살표만. 끝에서 나가는 버튼: 글자 있는 알약 모양(이전 자료 · 다음 자료)
661
+ const paint = (el, side, leaving, available) => {
662
+ const arrow = side === 'prev' ? '‹' : '›';
663
+ el.classList.toggle('leave', leaving);
664
+ el.hidden = leaving && !available;
665
+ if (leaving) {
666
+ const text = side === 'prev' ? '이전 자료' : '다음 자료';
667
+ el.textContent = side === 'prev' ? `${arrow} ${text}` : `${text} ${arrow}`;
668
+ el.setAttribute('aria-label', `${text}로 이동 (이 자료를 나갑니다)`);
669
+ el.title = `LXP ${side === 'prev' ? '이전' : '다음'} 수업 자료로 이동`;
670
+ } else {
671
+ el.textContent = arrow;
672
+ el.setAttribute('aria-label', side === 'prev' ? '이전 단계' : '다음 단계');
673
+ el.removeAttribute('title');
674
+ }
675
+ };
676
+ const render = () => {
677
+ paint(prev, 'prev', step === 0, edge.prev);
678
+ paint(next, 'next', step === total - 1, edge.next);
679
+ counter.textContent = `${step + 1} / ${total}`;
680
+ };
681
+ const go = (i) => {
682
+ const to = Math.min(Math.max(0, i), total - 1);
683
+ if (to === step) return;
684
+ step = to;
685
+ render();
686
+ onChange(step, { content: area });
687
+ };
688
+ const leave = (side) => {
689
+ try {
690
+ if (side === 'prev') app.navigation?.previous();
691
+ else app.navigation?.next();
692
+ } catch {
693
+ // 화면이 이동을 지원하지 않으면(편집 화면 등) 아무것도 하지 않는다
694
+ }
695
+ };
696
+ prev.addEventListener('click', () => (step === 0 ? leave('prev') : go(step - 1)));
697
+ next.addEventListener('click', () => (step === total - 1 ? leave('next') : go(step + 1)));
698
+
699
+ render();
700
+ onChange(step, { content: area });
701
+ const ready = Promise.all([hasLecturePage(app, 'prev'), hasLecturePage(app, 'next')]).then(
702
+ ([p, n]) => {
703
+ edge.prev = p;
704
+ edge.next = n;
705
+ render();
706
+ },
707
+ );
708
+ return {
709
+ element: frame,
710
+ content: area,
711
+ ready,
712
+ go,
713
+ get step() {
714
+ return step;
715
+ },
716
+ };
717
+ }
718
+
719
+ function mountSave(app, { getContent, getGrading, validate, root, label = '저장' }) {
461
720
  if (app.screen !== 'edit') throw new Error('useSave는 편집 화면(screen: edit)에서만 씁니다.');
462
721
  const area = appRoot(root);
463
722
  const status = h('p', { className: 'ec-muted', role: 'status' });
464
723
  const button = h('button', { className: 'ec-primary', type: 'button', textContent: label });
465
724
  const bar = h('div', { className: 'ec-submitbar' });
466
725
  bar.append(status, button);
467
- area.after(bar);
726
+ // 채점 방식 블록(useGradingBlock)이 화면 영역 바로 뒤에 있으면 그 뒤에 둔다
727
+ let anchor = area;
728
+ while (anchor.nextElementSibling?.classList.contains('ec-grading')) anchor = anchor.nextElementSibling;
729
+ anchor.after(bar);
468
730
 
469
731
  let dirty = false;
470
732
  const markDirty = () => {
471
733
  dirty = true;
734
+ // 이제 이 버튼이 실제 저장이라 (LXP 하단 저장은 settings를 저장하지 않음) 저장 전 상태는 이 문구가 유일한 안내
472
735
  status.textContent = '저장하지 않은 변경이 있어요.';
473
736
  };
474
737
  area.addEventListener('input', markDirty);
475
738
  area.addEventListener('change', markDirty);
739
+ // 채점 방식 블록은 화면 영역 밖에 붙는다: 거기서 바꿔도 저장 전 표시
740
+ const scope = area.parentElement;
741
+ const inBlock = e => e.target instanceof Element && e.target.closest('.ec-grading');
742
+ scope?.addEventListener('input', e => inBlock(e) && markDirty());
743
+ scope?.addEventListener('change', e => inBlock(e) && markDirty());
476
744
  // 문항 추가 · 삭제처럼 입력 없이 화면이 바뀌는 경우
477
745
  if (typeof MutationObserver !== 'undefined') {
478
746
  let ready = false;
@@ -482,17 +750,15 @@ function mountSave(app, { getContent, validate, root, label = '저장' }) {
482
750
  subtree: true,
483
751
  });
484
752
  }
485
- globalThis.addEventListener?.('beforeunload', (e) => {
753
+ globalThis.addEventListener?.('beforeunload', e => {
486
754
  if (dirty) e.preventDefault();
487
755
  });
488
756
 
489
- // 실제 SDK의 saveSettings는 편집 페이지에 넘기기만 한다. 자료를 저장해야 학생 화면에 반영된다
757
+ // 실제 SDK의 saveSettings는 edit 토큰으로 서버에 바로 저장한다 (새 버전, 학생 화면에 바로 반영)
490
758
  const savedText = () =>
491
759
  app.sdkKind === 'mock'
492
760
  ? '저장했어요 (mock · 이 브라우저에만).'
493
- : app.isLocal
494
- ? '로컬 미리보기라 저장되지 않았어요.'
495
- : '편집 페이지에 넘겼어요. 자료를 저장하면 학생 화면에 반영됩니다.';
761
+ : '저장했어요. 학생 화면에 반영됩니다.';
496
762
 
497
763
  button.addEventListener('click', async () => {
498
764
  const next = getContent();
@@ -501,19 +767,366 @@ function mountSave(app, { getContent, validate, root, label = '저장' }) {
501
767
  status.textContent = typeof ok === 'string' ? ok : '내용을 확인해 주세요.';
502
768
  return;
503
769
  }
770
+ const gradingPart = getGrading ? getGrading() : undefined;
771
+ if (typeof gradingPart === 'string') {
772
+ status.textContent = gradingPart;
773
+ return;
774
+ }
775
+ button.disabled = true;
776
+ try {
777
+ await app.saveContent(next, gradingPart ?? undefined);
778
+ dirty = false;
779
+ status.textContent = savedText();
780
+ } catch (e) {
781
+ // 로컬에서 실제 SDK로 연 draft(#edit=1)는 저장할 곳이 없다
782
+ status.textContent =
783
+ e.code === 'draft_not_saved' && app.isLocal
784
+ ? '로컬 미리보기라 저장되지 않았어요.'
785
+ : `저장하지 못했어요: ${e.message}`;
786
+ } finally {
787
+ button.disabled = false;
788
+ }
789
+ });
790
+ return {
791
+ element: bar,
792
+ markDirty,
793
+ get dirty() {
794
+ return dirty;
795
+ },
796
+ };
797
+ }
798
+
799
+ /**
800
+ * @typedef {object} GradingBlockOptions
801
+ * @property {Array<'pattern' | 'rubric'>} [graders] 고를 수 있는 채점 방식 (기본 둘 다)
802
+ * @property {Array<[string, string]>} [examples] '작성 예시 보기'에 보일 [정규식, 뜻] (기본 GRADING_EXAMPLES)
803
+ * @property {Element} [root] 블록을 넣을 곳 (기본: 화면 영역 #app 바로 뒤)
804
+ */
805
+
806
+ /**
807
+ * @typedef {object} CompletionOptions
808
+ * @property {Array<'on_access' | 'on_submit' | 'on_graded'>} [policies] 고를 수 있는 완료 정책
809
+ * (기본 metadata completionPolicies, 서버가 주지 않으면 셋 다)
810
+ * @property {Element} [root] 넣을 곳 (기본: 화면 영역 #app을 이 영역으로 채움)
811
+ * @property {string} [label] 버튼 글자 (기본 '저장')
812
+ */
813
+
814
+ /** 완료 정책 문구 (ADR 0009). 열람 · 제출은 LXP 설정 탭 문구 그대로 (qa5 2026-11-10) */
815
+ export const COMPLETION_POLICIES = Object.freeze({
816
+ on_access: {
817
+ label: '열람 시 학습 완료',
818
+ description: "자료를 열면 학습 완료로 처리됩니다. 학생 화면에는 점수 대신 '완료'로 표시됩니다.",
819
+ },
820
+ on_submit: {
821
+ label: '제출 시 학습 완료',
822
+ description:
823
+ "답과 관계없이 제출하면 학습 완료로 처리됩니다. 학생 화면에는 점수 대신 '완료'로 표시됩니다.",
824
+ },
825
+ on_graded: {
826
+ label: '채점해 통과하면 학습 완료',
827
+ description:
828
+ '제출한 답을 편집 화면에서 정한 채점 방식으로 채점하고, 통과하면 학습 완료로 처리됩니다.',
829
+ },
830
+ });
831
+
832
+ /** 채점 방식 문구 (settings.grading.type, LXP 설정 탭 문구 그대로) */
833
+ export const GRADER_TYPES = Object.freeze({
834
+ pattern: {
835
+ label: '기준 답안과 비교해 채점',
836
+ description: '학생이 제출한 답안을 기준 답안의 패턴과 비교해 채점합니다.',
837
+ },
838
+ rubric: {
839
+ label: '입력한 평가 기준으로 채점',
840
+ description: 'AI가 학생의 답을 읽고 점수를 매깁니다.',
841
+ },
842
+ });
843
+
844
+ /** '작성 예시 보기' 기본 예시: [정규식, 뜻]. 학생 답(앞뒤 공백을 자른 문자열) 전체와 맞으면 정답 */
845
+ export const GRADING_EXAMPLES = Object.freeze([
846
+ ['^서울$', '"서울"만 정답'],
847
+ ['^서울(시|특별시)?$', '"서울" · "서울시" · "서울특별시" 정답'],
848
+ ['^(가중치|weight)$', '"가중치" 또는 "weight" 정답'],
849
+ ['^4[0-9]$', '40 ~ 49 정답'],
850
+ ]);
851
+
852
+ const GRADING_TEXT = {
853
+ heading: '채점 방식',
854
+ headingHelp: '제출한 답을 어떻게 채점할지와 기준 답안 · 평가 기준을 정합니다.',
855
+ answerKey: '기준 답안 (정규표현식)',
856
+ answerKeyPlaceholder: '예: ^서울(시|특별시)?$',
857
+ answerKeyHelp: '정답으로 인정할 답안의 패턴을 입력해 주세요.',
858
+ examples: '작성 예시 보기',
859
+ examplesClose: '작성 예시 닫기',
860
+ rubric: '평가 기준',
861
+ rubricPlaceholder: '예: 핵심 개념 2개 이상을 정확히 설명하면 만점',
862
+ emptyRubric: '평가 기준을 입력해 주세요.',
863
+ };
864
+
865
+ const COMPLETION_TEXT = {
866
+ heading: '완료 정책',
867
+ headingHelp: '학습 완료를 언제 기록할지 고릅니다: 열면, 제출하면, 채점해 통과하면.',
868
+ grader: name => `채점 방식: ${name} (편집 화면에서 정함)`,
869
+ noGrader: '채점 방식과 답이 아직 없습니다. 편집 화면에서 먼저 정해 주세요.',
870
+ loading: '완료 정책을 불러오는 중…',
871
+ };
872
+
873
+ /** 정답 정규식 길이 상한 (서버에 보내는 값, 너무 긴 정규식은 막는다) */
874
+ export const ANSWER_KEY_MAX = 5000;
875
+ /** 정답 정규식 한 번 맞춰 보는 시간 상한(ms). 넘으면 ReDoS 위험으로 막는다 */
876
+ const REGEX_TIME_LIMIT_MS = 50;
877
+
878
+ /**
879
+ * 정답 정규식 공통 검사 (ADR 0009): 비어 있지 않음 · 길이 · 컴파일 · `^…$`로 감쌈(부분 일치 방지) · 실행 시간(ReDoS).
880
+ * samples(맞춰 볼 문자열)도 같이 시간을 잰다. 문제가 없으면 null, 있으면 보여 줄 문장
881
+ * @param {string} regex
882
+ * @param {string[]} [samples]
883
+ * @returns {string | null}
884
+ */
885
+ export function validateAnswerRegex(regex, samples = []) {
886
+ const key = typeof regex === 'string' ? regex.trim() : '';
887
+ if (!key) return '기준 답안(정규표현식)을 입력해 주세요.';
888
+ if (key.length > ANSWER_KEY_MAX)
889
+ return `기준 답안이 너무 깁니다 (${key.length}자, 최대 ${ANSWER_KEY_MAX}자).`;
890
+ let re;
891
+ try {
892
+ re = new RegExp(key);
893
+ } catch (e) {
894
+ return `기준 답안이 올바른 정규표현식이 아닙니다: ${e.message}`;
895
+ }
896
+ if (!key.startsWith('^') || !key.endsWith('$') || /(^|[^\\])(\\\\)*\\\$$/.test(key))
897
+ return '기준 답안은 ^로 시작해 $로 끝나야 합니다 (답 전체와 맞춰야 부분만 맞아도 정답이 되지 않음).';
898
+ const now = () => (typeof performance === 'undefined' ? Date.now() : performance.now());
899
+ const slow = text => {
900
+ const started = now();
901
+ re.test(text);
902
+ return now() - started > REGEX_TIME_LIMIT_MS;
903
+ };
904
+ const tooSlow =
905
+ '기준 답안을 맞춰 보는 데 너무 오래 걸립니다. 반복(*, +)이 겹치지 않게 고쳐 주세요.';
906
+ if (samples.some(slow)) return tooSlow;
907
+ // 겹친 반복(예: (a+)+)은 길이가 늘수록 시간이 두 배씩 는다: 짧은 길이부터 늘려 가며 재고, 느려지면 바로 멈춘다
908
+ // (긴 문자열을 한 번에 넣으면 멈추지 않을 수 있다)
909
+ const chars = [...new Set(key.replace(/\\./g, '').match(/[A-Za-z0-9가-힣%=;,]/g) ?? ['a'])].slice(0, 4);
910
+ for (const c of chars)
911
+ for (let n = 8; n <= 28; n += 2) if (slow(`${c.repeat(n)}\u0000`)) return tooSlow;
912
+ return null;
913
+ }
914
+
915
+ /** 라디오 카드 하나 (LXP 설정 탭 모양) */
916
+ function radioCard(name, value, info, checked) {
917
+ const card = h('label', { className: 'ec-grading-type' });
918
+ const input = h('input', { type: 'radio', name, value, checked });
919
+ const text = h('span', { className: 'ec-grading-text' });
920
+ text.append(
921
+ h('span', { className: 'ec-grading-label', textContent: info.label }),
922
+ h('span', { className: 'ec-muted', textContent: info.description })
923
+ );
924
+ card.append(input, text);
925
+ return { card, input };
926
+ }
927
+
928
+ function mountGradingBlock(app, { graders = ['pattern', 'rubric'], examples = GRADING_EXAMPLES, root }) {
929
+ if (app.screen !== 'edit')
930
+ throw new Error('useGradingBlock은 편집 화면(screen: edit)에서 씁니다.');
931
+ const t = GRADING_TEXT;
932
+ const name = `ec-grader-${Math.random().toString(36).slice(2, 8)}`;
933
+ const section = h('section', { className: 'ec-grading' });
934
+ const head = h('div', { className: 'ec-grading-head' });
935
+ head.append(
936
+ h('h2', { textContent: t.heading }),
937
+ h('p', { className: 'ec-muted', textContent: t.headingHelp })
938
+ );
939
+ const group = h('div', { className: 'ec-grading-types', role: 'radiogroup' });
940
+ group.setAttribute('aria-label', t.heading);
941
+ section.append(head, group);
942
+ if (root) root.append(section);
943
+ else appRoot(undefined).after(section);
944
+
945
+ const saved = app.grading;
946
+ let current = graders.includes(saved?.type) ? saved.type : graders[0];
947
+
948
+ // 기준 답안(pattern): LXP와 같은 정규식 칸 + 작성 예시
949
+ const keyId = `${name}-key`;
950
+ const keyInput = h('input', {
951
+ id: keyId,
952
+ type: 'text',
953
+ placeholder: t.answerKeyPlaceholder,
954
+ spellcheck: false,
955
+ });
956
+ keyInput.className = 'ec-grading-key';
957
+ keyInput.value = saved?.answer_key ?? '';
958
+ const toggle = h('button', { type: 'button', className: 'ec-text-button', textContent: t.examples });
959
+ const exampleList = h('dl', { className: 'ec-grading-examples', hidden: true });
960
+ for (const [regex, meaning] of examples)
961
+ exampleList.append(h('dt', { textContent: regex }), h('dd', { textContent: meaning }));
962
+ toggle.addEventListener('click', () => {
963
+ exampleList.hidden = !exampleList.hidden;
964
+ toggle.textContent = exampleList.hidden ? t.examples : t.examplesClose;
965
+ });
966
+ const labelRow = h('div', { className: 'ec-grading-field-head' });
967
+ labelRow.append(h('label', { textContent: t.answerKey, htmlFor: keyId }), toggle);
968
+ const regexDetail = h('div', { className: 'ec-grading-detail ec-grading-field' });
969
+ regexDetail.append(
970
+ labelRow,
971
+ exampleList,
972
+ keyInput,
973
+ h('p', { className: 'ec-muted', textContent: t.answerKeyHelp })
974
+ );
975
+ // 평가 기준(rubric)
976
+ const rubricId = `${name}-rubric`;
977
+ const rubricInput = h('textarea', { id: rubricId, placeholder: t.rubricPlaceholder, rows: 4 });
978
+ rubricInput.className = 'ec-grading-rubric';
979
+ rubricInput.value = saved?.rubric ?? '';
980
+ const rubricDetail = h('div', { className: 'ec-grading-detail' });
981
+ rubricDetail.append(h('label', { textContent: t.rubric, htmlFor: rubricId }), rubricInput);
982
+ const details = { pattern: regexDetail, rubric: rubricDetail };
983
+
984
+ const cards = graders.map(type => {
985
+ const { card, input } = radioCard(name, type, GRADER_TYPES[type] ?? { label: type, description: '' }, type === current);
986
+ const wrap = h('div', { className: 'ec-grading-item' });
987
+ wrap.append(card, details[type]);
988
+ input.addEventListener('change', () => select(type));
989
+ group.append(wrap);
990
+ return { type, card };
991
+ });
992
+ function select(type) {
993
+ current = type;
994
+ for (const c of cards) c.card.classList.toggle('selected', c.type === type);
995
+ for (const [ty, detail] of Object.entries(details)) detail.hidden = ty !== type;
996
+ }
997
+ select(current);
998
+
999
+ return {
1000
+ element: section,
1001
+ get grader() {
1002
+ return current;
1003
+ },
1004
+ /** 저장할 채점 설정 `{ type: 'pattern', answer_key }` · `{ type: 'rubric', rubric }`, 문제가 있으면 문장 (useSave getGrading에 넘김) */
1005
+ getGrading() {
1006
+ if (current === 'pattern') {
1007
+ const key = keyInput.value.trim();
1008
+ const problem = validateAnswerRegex(key);
1009
+ return problem ?? { type: 'pattern', answer_key: key };
1010
+ }
1011
+ const rubric = rubricInput.value.trim();
1012
+ return rubric ? { type: 'rubric', rubric } : t.emptyRubric;
1013
+ },
1014
+ };
1015
+ }
1016
+
1017
+ function mountCompletion(app, { policies = app.completion.policies ?? POLICY_VALUES, root, label = '저장' }) {
1018
+ if (app.screen !== 'completionPolicy')
1019
+ throw new Error('useCompletion은 완료 정책 화면(screen: completionPolicy)에서만 씁니다.');
1020
+ const t = COMPLETION_TEXT;
1021
+ const area = appRoot(root);
1022
+ const name = `ec-completion-${Math.random().toString(36).slice(2, 8)}`;
1023
+ const section = h('section', { className: 'ec-grading' });
1024
+ const head = h('div', { className: 'ec-grading-head' });
1025
+ head.append(
1026
+ h('h2', { textContent: t.heading }),
1027
+ h('p', { className: 'ec-muted', textContent: t.headingHelp })
1028
+ );
1029
+ const group = h('div', { className: 'ec-grading-types', role: 'radiogroup' });
1030
+ group.setAttribute('aria-label', t.heading);
1031
+ section.append(head, group);
1032
+ // 완료 정책 화면은 이 영역이 화면 전부라 기본 영역(#app)의 "불러오는 중"을 비운다. root를 주면 그 뒤에 더한다
1033
+ if (root) area.append(section);
1034
+ else area.replaceChildren(section);
1035
+
1036
+ let current = policies[0];
1037
+ const graderInfo = GRADER_TYPES[app.grading?.type];
1038
+
1039
+ // 채점해 통과(on_graded): 편집 화면이 정한 채점 방식을 보여 준다
1040
+ const gradedDetail = h('div', { className: 'ec-grading-detail' });
1041
+ gradedDetail.append(
1042
+ h('p', {
1043
+ className: graderInfo ? 'ec-muted' : 'ec-error',
1044
+ textContent: graderInfo ? t.grader(graderInfo.label) : t.noGrader,
1045
+ })
1046
+ );
1047
+
1048
+ const cards = policies.map(policy => {
1049
+ const { card, input } = radioCard(name, policy, COMPLETION_POLICIES[policy] ?? { label: policy, description: '' }, policy === current);
1050
+ const wrap = h('div', { className: 'ec-grading-item' });
1051
+ wrap.append(card);
1052
+ if (policy === 'on_graded') wrap.append(gradedDetail);
1053
+ input.addEventListener('change', () => select(policy));
1054
+ group.append(wrap);
1055
+ return { policy, card, input };
1056
+ });
1057
+ function select(policy) {
1058
+ current = policy;
1059
+ for (const c of cards) {
1060
+ c.card.classList.toggle('selected', c.policy === policy);
1061
+ c.input.checked = c.policy === policy;
1062
+ }
1063
+ gradedDetail.hidden = policy !== 'on_graded';
1064
+ }
1065
+ select(current);
1066
+
1067
+ const status = h('p', { className: 'ec-muted', role: 'status', textContent: t.loading });
1068
+ const error = h('p', { className: 'ec-error', role: 'alert' });
1069
+ const button = h('button', { className: 'ec-primary', type: 'button', textContent: label, disabled: true });
1070
+ const bar = h('div', { className: 'ec-submitbar' });
1071
+ bar.append(status, error, button);
1072
+ area.after(bar);
1073
+
1074
+ let dirty = false;
1075
+ const markDirty = () => {
1076
+ dirty = true;
1077
+ status.textContent = '저장하지 않은 변경이 있어요.';
1078
+ };
1079
+ area.addEventListener('input', markDirty);
1080
+ area.addEventListener('change', markDirty);
1081
+ globalThis.addEventListener?.('beforeunload', e => {
1082
+ if (dirty) e.preventDefault();
1083
+ });
1084
+
1085
+ // 지금 완료 정책 (완료 정책 API · ecdk dev 흉내). 지원되지 않으면 저장을 막고 이유를 보여 준다
1086
+ const ready = app.completion.get().then(
1087
+ ({ completion_policy: policy }) => {
1088
+ if (policies.includes(policy)) select(policy);
1089
+ status.textContent = '';
1090
+ button.disabled = false;
1091
+ },
1092
+ e => {
1093
+ status.textContent = '';
1094
+ error.textContent = e.message;
1095
+ }
1096
+ );
1097
+
1098
+ const savedText = () =>
1099
+ app.sdkKind === 'mock'
1100
+ ? '저장했어요 (mock · 이 브라우저에만).'
1101
+ : '저장했어요. 다음 제출부터 이 완료 정책을 씁니다.';
1102
+
1103
+ button.addEventListener('click', async () => {
1104
+ if (current === 'on_graded' && !graderInfo) {
1105
+ error.textContent = t.noGrader;
1106
+ return;
1107
+ }
1108
+ error.textContent = '';
504
1109
  button.disabled = true;
1110
+ button.setAttribute('aria-busy', 'true');
505
1111
  try {
506
- await app.saveContent(next);
1112
+ await app.completion.set(current);
507
1113
  dirty = false;
508
1114
  status.textContent = savedText();
509
1115
  } catch (e) {
510
- status.textContent = `저장하지 못했어요: ${e.message}`;
1116
+ status.textContent = '';
1117
+ error.textContent = e.message;
511
1118
  } finally {
512
1119
  button.disabled = false;
1120
+ button.removeAttribute('aria-busy');
513
1121
  }
514
1122
  });
515
1123
  return {
516
1124
  element: bar,
1125
+ /** 지금 완료 정책을 불러온 뒤 끝나는 Promise */
1126
+ ready,
1127
+ get policy() {
1128
+ return current;
1129
+ },
517
1130
  markDirty,
518
1131
  get dirty() {
519
1132
  return dirty;