@eliceio/cdk-cli 1.6.0 → 1.7.0

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 (63) hide show
  1. package/es/commands/create/scaffold.d.ts +1 -1
  2. package/es/commands/create/scaffold.js +1 -1
  3. package/es/commands/dev/index.d.ts +1 -1
  4. package/es/commands/dev/index.js +1 -1
  5. package/es/core/quiz-check.js +5 -5
  6. package/es/dev/host-page.js +19 -3
  7. package/es/dev/kv-public-mock.d.ts +101 -0
  8. package/es/dev/kv-public-mock.js +489 -0
  9. package/es/dev/mock-api.d.ts +28 -6
  10. package/es/dev/mock-api.js +57 -59
  11. package/es/dev/mock-http.d.ts +28 -0
  12. package/es/dev/mock-http.js +53 -0
  13. package/es/dev/server.js +8 -3
  14. package/package.json +8 -7
  15. package/skills/_shared/references/02-design-the-material.md +1 -1
  16. package/skills/_shared/references/06-using-the-quiz-template.md +1 -0
  17. package/templates/_shared/lib/cdk-mock.d.ts +37 -0
  18. package/templates/_shared/lib/cdk-mock.js +89 -1
  19. package/templates/_shared/lib/elice-content.d.ts +5 -0
  20. package/templates/_shared/lib/elice-content.js +7 -0
  21. package/templates/board/README.md +118 -0
  22. package/templates/board/commentary.txt +6 -0
  23. package/templates/board/core/board.d.ts +176 -0
  24. package/templates/board/core/board.js +732 -0
  25. package/templates/board/core/dom.d.ts +13 -0
  26. package/templates/board/core/dom.js +83 -0
  27. package/templates/board/core/model.d.ts +58 -0
  28. package/templates/board/core/model.js +217 -0
  29. package/templates/board/core/settings.d.ts +44 -0
  30. package/templates/board/core/settings.js +131 -0
  31. package/templates/board/edit.html +23 -0
  32. package/templates/board/gitignore +4 -0
  33. package/templates/board/index.html +22 -0
  34. package/templates/board/instructor.html +23 -0
  35. package/templates/board/metadata.json +9 -0
  36. package/templates/board/package.json +13 -0
  37. package/templates/board/screens/board.js +318 -0
  38. package/templates/board/screens/edit.js +631 -0
  39. package/templates/board/screens/instructor.js +16 -0
  40. package/templates/board/screens/learn.js +14 -0
  41. package/templates/board/template.json +14 -0
  42. package/templates/board/ui/background.css +8 -0
  43. package/templates/board/ui/board-bg.webp +0 -0
  44. package/templates/board/ui/board.css +1124 -0
  45. package/templates/board/ui/card.js +141 -0
  46. package/templates/board/ui/composer.js +329 -0
  47. package/templates/board/ui/dropdown.js +185 -0
  48. package/templates/board/ui/icons.js +36 -0
  49. package/templates/board/ui/learn.css +141 -0
  50. package/templates/board/ui/menu.js +104 -0
  51. package/templates/board/ui/texts.d.ts +3 -0
  52. package/templates/board/ui/texts.js +162 -0
  53. package/templates/quiz/README.md +16 -6
  54. package/templates/quiz/core/draft.d.ts +32 -0
  55. package/templates/quiz/core/draft.js +224 -0
  56. package/templates/quiz/core/model.d.ts +5 -8
  57. package/templates/quiz/core/model.js +11 -13
  58. package/templates/quiz/screens/edit.js +8 -18
  59. package/templates/quiz/screens/learn.js +62 -13
  60. package/templates/quiz/styles.css +3 -6
  61. package/templates/quiz/template.json +1 -1
  62. package/templates/quiz/ui/templates/page.js +1 -14
  63. package/templates/quiz/ui/texts.js +1 -5
@@ -1,5 +1,7 @@
1
1
  import { parseGrading, serverGradingError } from '../core/config.js';
2
2
  import { answerError, hasRubricAnswers, grade, completionScore, recommendedCompletionPolicy } from './grading.js';
3
+ import { handlePublicKvApi, touchesPublic, notifyPublicChange, PUBLIC_MAX_BYTES, createPublicKvStore } from './kv-public-mock.js';
4
+ import { fail, readClaims, body, send } from './mock-http.js';
3
5
 
4
6
  /**
5
7
  * elice-material API 흉내 (서버 설계 v25, @eliceio/cdk 1.x가 부르는 것만).
@@ -11,11 +13,25 @@ const STUDENT = {
11
13
  anonymous_id: 'dev-student',
12
14
  fullname: '김하늘 (dev)'
13
15
  };
16
+ /** 학생 여럿 (보드를 여러 탭에서 볼 때): 보기 `student:2` · `student:3` */
17
+ const STUDENT_2 = {
18
+ account_id: 2,
19
+ anonymous_id: 'dev-student-2',
20
+ fullname: '이바다 (dev)'
21
+ };
22
+ const STUDENT_3 = {
23
+ account_id: 3,
24
+ anonymous_id: 'dev-student-3',
25
+ fullname: '박구름 (dev)'
26
+ };
14
27
  const MANAGER = {
15
28
  account_id: 100,
16
29
  anonymous_id: 'dev-manager',
17
30
  fullname: '교육자 (dev)'
18
31
  };
32
+ const ACCOUNTS = [STUDENT, STUDENT_2, STUDENT_3, MANAGER];
33
+ /** 계정 id → 익명 id · 이름. 모르는 계정은 첫 학생으로 본다 */
34
+ const accountOf = accountId => ACCOUNTS.find(a => a.account_id === accountId) ?? STUDENT;
19
35
  /** settings.entry.startProject가 묶은 작품 모양 { enc, data }인가 (엔트리 AI 채점 저장 조건) */
20
36
  function hasEntryStartProject(settings) {
21
37
  const entry = settings.entry;
@@ -25,19 +41,34 @@ function hasEntryStartProject(settings) {
25
41
  const TOKEN_SCENARIOS = Object.freeze({
26
42
  edit: {
27
43
  scope: 'edit',
28
- viewer: 'instructor'
44
+ viewer: 'instructor',
45
+ subject: MANAGER
29
46
  },
30
47
  instructor: {
31
48
  scope: 'learn',
32
- viewer: 'instructor'
49
+ viewer: 'instructor',
50
+ subject: MANAGER
33
51
  },
34
52
  student: {
35
53
  scope: 'learn',
36
- viewer: 'student'
54
+ viewer: 'student',
55
+ subject: STUDENT
56
+ },
57
+ 'student:2': {
58
+ scope: 'learn',
59
+ viewer: 'student',
60
+ subject: STUDENT_2
37
61
  },
62
+ 'student:3': {
63
+ scope: 'learn',
64
+ viewer: 'student',
65
+ subject: STUDENT_3
66
+ },
67
+ // 튜터는 첫 학생을 본다
38
68
  tutor: {
39
69
  scope: 'learn',
40
- viewer: 'tutor'
70
+ viewer: 'tutor',
71
+ subject: STUDENT
41
72
  }
42
73
  });
43
74
  const isTokenScenario = v => typeof v === 'string' && Object.hasOwn(TOKEN_SCENARIOS, v);
@@ -52,9 +83,9 @@ const sign = claims => `${b64url(JSON.stringify({
52
83
  function issueToken(scenario, ttlSeconds = TOKEN_TTL_SECONDS) {
53
84
  const {
54
85
  scope,
55
- viewer
86
+ viewer,
87
+ subject
56
88
  } = TOKEN_SCENARIOS[scenario];
57
- const subject = viewer === 'instructor' ? MANAGER : STUDENT;
58
89
  const now = nowSeconds();
59
90
  return sign({
60
91
  material_id: DEV_MATERIAL_ID,
@@ -68,16 +99,6 @@ function issueToken(scenario, ttlSeconds = TOKEN_TTL_SECONDS) {
68
99
  exp: now + ttlSeconds
69
100
  });
70
101
  }
71
- function readClaims(req) {
72
- const auth = req.headers.authorization ?? '';
73
- const token = auth.replace(/^Bearer\s+/i, '');
74
- try {
75
- const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());
76
- return claims.exp * 1000 > Date.now() ? claims : null;
77
- } catch {
78
- return null;
79
- }
80
- }
81
102
  const createState = () => ({
82
103
  settings: {},
83
104
  version: 1,
@@ -85,21 +106,13 @@ const createState = () => ({
85
106
  results: new Map(),
86
107
  recent: new Map(),
87
108
  kv: new Map(),
88
- completionPolicy: null
109
+ completionPolicy: null,
110
+ publicKv: createPublicKvStore()
89
111
  });
90
112
  /** 지금 쓰는 완료 정책: 고른 값, 없으면 권장값 */
91
113
  const effectiveCompletionPolicy = (state, local) => state.completionPolicy ?? recommendedCompletionPolicy(local);
92
114
  const MAX_ANSWER_BYTES = 64 * 1024;
93
115
  const RATE_PER_MINUTE = 30;
94
- function send(res, status, data) {
95
- res.writeHead(status, {
96
- 'Content-Type': 'application/json; charset=utf-8'
97
- });
98
- res.end(JSON.stringify({
99
- data,
100
- meta: {}
101
- }));
102
- }
103
116
  /** per_question AI 채점 흉내의 기다림 (서버는 묶음 run 한 번에 몇 초). 채점 중 화면을 dev에서 보려고 */
104
117
  const RUBRIC_DELAY_MS = 1200;
105
118
  /**
@@ -107,37 +120,6 @@ const RUBRIC_DELAY_MS = 1200;
107
120
  * dev에서 거절 화면을 보려고 노골적인 문구 몇 개만
108
121
  */
109
122
  const GUARD_REFUSAL = /이전 지시를 무시|지시를 무시하고|ignore (all |the )?(previous|prior|above) instructions/i;
110
- function fail(res, status, code, message, details = []) {
111
- res.writeHead(status, {
112
- 'Content-Type': 'application/json; charset=utf-8'
113
- });
114
- res.end(JSON.stringify({
115
- data: null,
116
- meta: {
117
- error: {
118
- code,
119
- message,
120
- details
121
- }
122
- }
123
- }));
124
- }
125
- async function body(req) {
126
- const chunks = [];
127
- for await (const c of req) chunks.push(c);
128
- const raw = Buffer.concat(chunks).toString();
129
- try {
130
- return {
131
- raw,
132
- json: raw ? JSON.parse(raw) : null
133
- };
134
- } catch {
135
- return {
136
- raw,
137
- json: null
138
- };
139
- }
140
- }
141
123
  const emptyResult = () => ({
142
124
  score: null,
143
125
  submit_count: 0,
@@ -258,6 +240,10 @@ async function handleMockApi(req, res, path, opts) {
258
240
  log('자료 파일 업로드 주소를 발급했습니다');
259
241
  return send(res, 200, r.data);
260
242
  }
243
+ // 공개 kv: 모두의 public 줄 · 입장권 · SSE (kv-public-mock.ts). SSE는 토큰 대신 입장권(ticket)으로 연다
244
+ if (await handlePublicKvApi(req, res, path, {
245
+ store: state.publicKv,
246
+ kv: state.kv})) return;
261
247
  const m = path.match(/^\/materials\/([0-9a-f-]{36})(\/me|\/draft|\/submissions|\/submissions\/me|\/kv\/account|\/learner-files\/url)?$/);
262
248
  if (!m) return fail(res, 404, 'RESOURCE_NOT_FOUND', `no route: ${method} ${path}`);
263
249
  const claims = readClaims(req);
@@ -395,7 +381,7 @@ async function handleMockApi(req, res, path, opts) {
395
381
  });
396
382
  }
397
383
  if (method === 'GET' && sub === '/me') {
398
- const user = claims.viewer === 'instructor' ? MANAGER : STUDENT;
384
+ const user = accountOf(claims.account_id);
399
385
  if (policy === 'on_access' && claims.viewer === 'student') {
400
386
  const before = state.results.get(subject)?.completed_at ?? null;
401
387
  grantOnAccess(state, subject);
@@ -407,6 +393,8 @@ async function handleMockApi(req, res, path, opts) {
407
393
  viewer: claims.viewer,
408
394
  // 서버처럼 맨 위에 anonymous_id (`user`는 옛 SDK가 읽음)
409
395
  anonymous_id: user.anonymous_id,
396
+ // 패들릿 설계 v6: 보드가 자기 public 줄 알림을 거르는 데 쓴다 (서버 추가 예정)
397
+ account_id: claims.account_id,
410
398
  locale: claims.locale,
411
399
  completion_policy: policy,
412
400
  // 서버처럼 on_graded이고 채점 설정이 있을 때만
@@ -559,12 +547,22 @@ async function handleMockApi(req, res, path, opts) {
559
547
  const parent = kvRead(next, parts.join('.'));
560
548
  if (parent && typeof parent === 'object' && !Array.isArray(parent)) delete parent[last];
561
549
  state.kv.set(subject, next);
550
+ if (touchesPublic(key)) notifyPublicChange(state.publicKv, subject, claims.viewer);
562
551
  res.writeHead(204);
563
552
  return res.end();
564
553
  }
565
554
  const next = kvWrite(doc, key, value);
566
555
  if (typeof next === 'string') return fail(res, 409, 'MATERIAL_KV_PATH_CONFLICT', `"${next}" on the key path is not an object`);
556
+ // 공개 줄은 16 KB까지 (실제 백엔드: 409 MATERIAL_KV_QUOTA_EXCEEDED, reason public_too_large)
557
+ if (touchesPublic(key) && Buffer.byteLength(JSON.stringify(next.public)) > PUBLIC_MAX_BYTES) return fail(res, 409, 'MATERIAL_KV_QUOTA_EXCEEDED', `the public row would exceed ${PUBLIC_MAX_BYTES} bytes`, [{
558
+ ctx: {
559
+ reason: 'public_too_large',
560
+ limit_bytes: PUBLIC_MAX_BYTES,
561
+ total_bytes: Buffer.byteLength(JSON.stringify(next.public))
562
+ }
563
+ }]);
567
564
  state.kv.set(subject, next);
565
+ if (touchesPublic(key)) notifyPublicChange(state.publicKv, subject, claims.viewer);
568
566
  log(`kvstore: ${key} 저장`);
569
567
  return send(res, 200, {
570
568
  value
@@ -573,4 +571,4 @@ async function handleMockApi(req, res, path, opts) {
573
571
  return fail(res, 405, 'RESOURCE_NOT_FOUND', `${method} ${path}`);
574
572
  }
575
573
 
576
- export { DEV_MATERIAL_ID, MANAGER, STUDENT, TOKEN_SCENARIOS, createState, effectiveCompletionPolicy, handleMockApi, isTokenScenario, issueToken };
574
+ export { DEV_MATERIAL_ID, MANAGER, STUDENT, STUDENT_2, STUDENT_3, TOKEN_SCENARIOS, accountOf, createState, effectiveCompletionPolicy, handleMockApi, isTokenScenario, issueToken };
@@ -0,0 +1,28 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /**
3
+ * 흉내 API(mock-api.ts) · 공유 데이터 흉내(shared-mock.ts)가 같이 쓰는 토큰 · 응답 도우미.
4
+ * 응답은 elib 형식 `{ data, meta }`, 오류는 `{ data: null, meta: { error: { code, message, details } } }`
5
+ */
6
+ export type MaterialScope = 'learn' | 'edit';
7
+ export type MaterialViewer = 'student' | 'instructor' | 'tutor';
8
+ export interface Claims {
9
+ material_id: string;
10
+ scope: MaterialScope;
11
+ viewer: MaterialViewer;
12
+ /** 기록의 주인. tutor는 보고 있는 학생 */
13
+ account_id: number;
14
+ lecture_page_id: number;
15
+ course_id: number;
16
+ locale: string;
17
+ /** Unix seconds of the first token exchange */
18
+ session_started_at: number;
19
+ exp: number;
20
+ }
21
+ /** `Authorization: Bearer <token>`의 claim. 없거나 만료면 null (서명은 보지 않는다) */
22
+ export declare function readClaims(req: IncomingMessage): Claims | null;
23
+ export declare function send(res: ServerResponse, status: number, data: unknown): void;
24
+ export declare function fail(res: ServerResponse, status: number, code: string, message: string, details?: unknown[]): void;
25
+ export declare function body(req: IncomingMessage): Promise<{
26
+ raw: string;
27
+ json: unknown;
28
+ }>;
@@ -0,0 +1,53 @@
1
+ /** `Authorization: Bearer <token>`의 claim. 없거나 만료면 null (서명은 보지 않는다) */
2
+ function readClaims(req) {
3
+ const auth = req.headers.authorization ?? '';
4
+ const token = auth.replace(/^Bearer\s+/i, '');
5
+ try {
6
+ const claims = JSON.parse(Buffer.from(token.split('.')[1] ?? '', 'base64url').toString());
7
+ return claims.exp * 1000 > Date.now() ? claims : null;
8
+ } catch {
9
+ return null;
10
+ }
11
+ }
12
+ function send(res, status, data) {
13
+ res.writeHead(status, {
14
+ 'Content-Type': 'application/json; charset=utf-8'
15
+ });
16
+ res.end(JSON.stringify({
17
+ data,
18
+ meta: {}
19
+ }));
20
+ }
21
+ function fail(res, status, code, message, details = []) {
22
+ res.writeHead(status, {
23
+ 'Content-Type': 'application/json; charset=utf-8'
24
+ });
25
+ res.end(JSON.stringify({
26
+ data: null,
27
+ meta: {
28
+ error: {
29
+ code,
30
+ message,
31
+ details
32
+ }
33
+ }
34
+ }));
35
+ }
36
+ async function body(req) {
37
+ const chunks = [];
38
+ for await (const c of req) chunks.push(c);
39
+ const raw = Buffer.concat(chunks).toString();
40
+ try {
41
+ return {
42
+ raw,
43
+ json: raw ? JSON.parse(raw) : null
44
+ };
45
+ } catch {
46
+ return {
47
+ raw,
48
+ json: null
49
+ };
50
+ }
51
+ }
52
+
53
+ export { body, fail, readClaims, send };
package/es/dev/server.js CHANGED
@@ -15,6 +15,7 @@ import 'fflate';
15
15
  import { DEV_BLOB_PREFIX, handleBlobPut, ASSET_SIGNED_PATH, serveAsset, createUploadUrl, MOCK_UPLOAD_URL_PATH, removeAssets, assetStoragePath } from './assets.js';
16
16
  import { isCompletionPolicy, recommendedCompletionPolicy } from './grading.js';
17
17
  import { hostPage } from './host-page.js';
18
+ import { closePublicKv } from './kv-public-mock.js';
18
19
  import { handleLearnerBlobPut, serveLearnerFile, learnerFolderUrl, createLearnerUploadUrl, removeLearnerFiles } from './learner-files.js';
19
20
  import { DEV_MATERIAL_ID, handleMockApi, isTokenScenario, issueToken, createState } from './mock-api.js';
20
21
 
@@ -194,7 +195,7 @@ async function startDevServer(opts) {
194
195
  // 호스트 서버
195
196
  const cors = {
196
197
  'Access-Control-Allow-Origin': '*',
197
- 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Range',
198
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Range, If-None-Match',
198
199
  'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS'
199
200
  };
200
201
  // 올린 자료 파일 (asset_base_url + assets/{material_id}/{asset_key}), 흉내 API 출처
@@ -221,6 +222,8 @@ async function startDevServer(opts) {
221
222
  }
222
223
  if (url.pathname.startsWith('/api/')) {
223
224
  for (const [k, v] of Object.entries(cors)) res.setHeader(k, v);
225
+ // GET /kv/public의 ETag를 콘텐츠(다른 출처)가 읽어 If-None-Match로 보낸다
226
+ res.setHeader('Access-Control-Expose-Headers', 'ETag');
224
227
  await handleMockApi(req, res, url.pathname.slice(4), {
225
228
  state,
226
229
  getGrading: localGrading,
@@ -346,7 +349,8 @@ async function startDevServer(opts) {
346
349
  return;
347
350
  }
348
351
  if (url.pathname === '/__ecdk/reset' && req.method === 'POST') {
349
- // 고른 완료 정책은 기록이 아니라 dev 설정이라 그대로 둔다
352
+ // 고른 완료 정책은 기록이 아니라 dev 설정이라 그대로 둔다. 보드 실시간 연결은 닫아 SDK가 다시 구독하게 한다
353
+ closePublicKv(state.publicKv);
350
354
  Object.assign(state, {
351
355
  ...createState(),
352
356
  completionPolicy: state.completionPolicy
@@ -357,7 +361,7 @@ async function startDevServer(opts) {
357
361
  await removeAssets(dir);
358
362
  await removeLearnerFiles(dir);
359
363
  learnerUploadRate.clear();
360
- log(`[api] 저장 내용(${SETTINGS_DATA_FILE}) · 올린 파일 · 학생 파일 · 제출 기록을 지웠습니다`);
364
+ log(`[api] 저장 내용(${SETTINGS_DATA_FILE}) · 올린 파일 · 학생 파일 · 제출 기록 · 보드를 지웠습니다`);
361
365
  res.writeHead(204).end();
362
366
  return;
363
367
  }
@@ -478,6 +482,7 @@ async function startDevServer(opts) {
478
482
  watcher?.close();
479
483
  configWatcher?.close();
480
484
  for (const c of clients) c.end();
485
+ closePublicKv(state.publicKv);
481
486
  await vite?.close();
482
487
  const closing = Promise.all([new Promise(r => host.close(r)), new Promise(r => content.close(r))]);
483
488
  host.closeAllConnections();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eliceio/cdk-cli",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "교육자용 Custom HTML 콘텐츠 CLI",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -39,14 +39,15 @@
39
39
  "vite": "^8.3.6"
40
40
  },
41
41
  "devDependencies": {
42
- "@elice/rollup-config": "^1.260406.0",
43
- "@types/node": "^24.12.4",
42
+ "@elice/rollup-config": "5.261125.0",
43
+ "@elice/tsconfig": "5.261125.0",
44
+ "@types/node": "24.13.3",
44
45
  "cross-env": "^7.0.2",
45
46
  "del-cli": "^3.0.1",
46
- "rollup": "^4.0.0",
47
- "tslib": "^2.6.1",
48
- "typescript": "~5.9.3",
49
- "@eliceio/cdk": "^1.6.0"
47
+ "rollup": "4.62.4",
48
+ "tslib": "2.8.1",
49
+ "typescript": "6.0.3",
50
+ "@eliceio/cdk": "^1.7.0"
50
51
  },
51
52
  "scripts": {
52
53
  "prebuild": "del-cli \"buildcache/*\" \"es/*\"",
@@ -34,7 +34,7 @@ Read or watch / change values and observe (simulation, visualization) / follow s
34
34
  - **The grader and the answers are set on the edit screen** and saved to `settings.grading` with the edit token (`useSave` with `getGrading`): `{ "type": "pattern", "answer_key": "^…$" }` or `{ "type": "rubric", "rubric": "…" }`. The kit's default block `app.useGradingBlock()` uses LXP's wording (기준 답안 (정규표현식), 작성 예시 보기, 평가 기준). When the answers depend on the content's structure (questions, choices, steps), set them where the content is edited, for example in each question card. The answer to `pattern` is **one regular expression** that must match the whole submitted answer string (trimmed), so submit one string and build the regex from the instructor's choices.
35
35
  - **AI grading is `rubric`, saved on the edit screen.** AI가 답을 평가해 점수를 매기는 학습자료는 `settings.grading`을 `rubric`으로 저장한다 (편집 화면 `useSave`의 `getGrading`으로 평가 기준을 rubric 글로 만들어 저장), 학습 화면은 학습자 답만 제출한다, 화면에서 계산한 점수는 서버 채점에 쓰이지 않는다. Without `settings.grading`, `on_graded` scores 0 and never completes and `on_submit` gives 100 whatever the AI said. With `on_graded` + `rubric` the server grades 0–100 and completes at 1 point or more. Never compute the score with `mlapi` in the browser and submit it. Sketch and details: [5](05-screen-code.md) "AI grading".
36
36
  - **`partial_pattern` (partial score per question)**: `{ "type": "partial_pattern", "answer_key": ["^…$", "^…$"], "scores": [50, 50] }`. The student submits a **string array** in question order and `answer[i]` is matched against `answer_key[i]` the same way as `pattern` (trimmed, full match). The score is the sum of `scores[i]` of the matched questions, capped at 100. Rules the server enforces on save (422 otherwise): both arrays 1–50 long and the same length, each score an integer 0–100, the sum at least 100 (a lower sum could never complete). Only 100 is `is_correct: true` and completes `on_graded`; a missing item scores 0, extra items are ignored, and an answer that is not an array of strings is rejected (422). The response also carries `answer_correctness` (per question, `answer_key` order; `[]` for `pattern` · `rubric`), in the submit response and the submission lists, so a screen can mark each question right or wrong (SDK `answerCorrectness`). Kit helpers: `validatePartialGrading` (the same rules, for `getGrading`) and `splitScores(n)` (equal integer split summing to 100, e.g. 3 → [33, 33, 34]). The quiz template supports both (6).
37
- - **`per_question` (regex and AI-graded questions mixed, quiz template 1.11.0+)**: `{ "type": "per_question", "questions": [{ "score": 50, "grader": { "type": "pattern", "answer_key": "^q1=b$" } }, { "score": 50, "grader": { "type": "rubric", "rubric": "…", "question": "the problem text" } }], "pass_score": 60 }`. The answer is a string array in question order; an AI-graded item is the plain answer text (no `qN=`). A question earns `floor(grader score 0–100 × score / 100)`, the total is capped at 100, only 100 is `is_correct: true`, and `on_graded` completes at `pass_score` (1–100, default 100). Save rules (422 otherwise): 1–50 questions, integer scores summing to at least 100, at most 10 `rubric` graders, `rubric` ≤ 10,000 and `question` ≤ 2,000 characters. The response carries `question_results: [{ score, is_correct }]` per question (in the submission lists too). Use the quiz template's AI-graded question rather than writing this by hand.
37
+ - **`per_question` (regex and AI-graded questions mixed, quiz template 1.11.0+)**: `{ "type": "per_question", "questions": [{ "score": 50, "grader": { "type": "pattern", "answer_key": "^q1=b$" } }, { "score": 50, "grader": { "type": "rubric", "rubric": "…", "question": "the problem text" } }] }`. The answer is a string array in question order; an AI-graded item is the plain answer text (no `qN=`). A question earns `floor(grader score 0–100 × score / 100)`, the total is capped at 100, only 100 is `is_correct: true`, and `on_graded` completes only at 100 (the quiz template sets no pass score from 1.12.0 and drops an old `pass_score` when re-saved). Save rules (422 otherwise): 1–50 questions, integer scores summing to at least 100, at most 10 `rubric` graders, `rubric` ≤ 10,000 and `question` ≤ 2,000 characters. The response carries `question_results: [{ score, is_correct }]` per question (in the submission lists too). Use the quiz template's AI-graded question rather than writing this by hand.
38
38
  - **`entry` (Entry template only, two modes)**: `{ "type": "entry", "mode": "general", "answer_project": { "enc": "gzip+base64", "data": "…" } }` (compared with the answer project, 0 or 100; no other keys) or `{ "type": "entry", "mode": "ai", "answer_project": {…}, "rubrics": [{ "object": "ik8o", "criteria": "…", "score": 100 }] }` (`object` is an object id of the answer project — there is no whole-project criterion, `""` or an unknown id is rejected with 422 `entry_rubric_object_not_found`; the AI mode also needs `settings.entry.startProject`, and the general answer project needs at least one script or global list, else 422 `entry_answer_project_empty`; 1–10 criteria of 1–1,000 characters, integer scores 1–100 summing to 100; `question_results` and `grading_feedback.criteria` per criterion, in the submit response and in the submission history). The Entry template's edit screen saves it; do not write it by hand ([17](17-using-the-entry-template.md)).
39
39
  - **Choosing between `pattern` and `partial_pattern` is the person's call.** For a material with several questions, ask: "모두 맞혀야 100점" (`pattern`) or "문항별 부분 점수" (`partial_pattern`). For partial scores, take the per-question scores from the person or from the planning material; if neither gives them, use an equal score and say so in the summary (the quiz template's automatic score is `ceil(100 / questions)` each, 3 → 34 · 34 · 34; the kit's `splitScores` sums to exactly 100, 3 → 33 · 33 · 34). In the quiz template the author can also change the grader and the scores on the edit screen. Scores are integers 0–100 summing to at least 100 (usually exactly 100). Students must answer every question before they submit (the quiz blocks an unanswered question), so a skipped question cannot score 0 by design.
40
40
  - **Regexes run on the server in Python `re`**, not JavaScript: for a case-insensitive match put `(?i)` at the very start (`(?i)^(paris|파리)$`); the kit, `ecdk dev` and the local mock turn a leading `(?i)` · `(?s)` · `(?m)` into the JS flag. Avoid what the two engines read differently: `\w` · `\d` · `\b` match Unicode (Korean letters, full-width digits) in Python but only ASCII in JS, so write the characters out (`[0-9]`, `[가-힣A-Za-z]`); named groups are `(?P<name>…)` in Python and `(?<name>…)` in JS (do not use them); lookbehind must be fixed-width in Python; inline flags anywhere but the start fail in both. The generated keys (escaped literals, `(?:…|…)`, `^…$`) mean the same in both.
@@ -3,6 +3,7 @@
3
3
  - The quiz has **no instructor screen** (`metadata.json` `screens.instructor.enabled: false`): an instructor who opens it in LXP gets the student screen and can solve and submit it (graded, not recorded). Add `instructor.html` and turn it on only when the person asks for one; it shows only in the LXP editor preview (instructor switch), and instructors on the learning page still get the student screen.
4
4
  - The template starts with **no questions**: the student screen shows "학습 자료를 준비하고 있어요" until the edit screen saves. The questions and answers are added on the edit screen ("+ 문제 추가", any of the five types picked from the type button's list, the answer in the same card; up to 20 questions): in `ecdk dev`, so the upload can carry them (`.ecdk/settings.json`, sent after the person agrees), or on the LXP edit screen after upload. There is no quiz title or description field (the student screen starts with the questions); a `title` · `description` saved earlier is kept as is.
5
5
  - Question types: `select_one` · `select_multiple` · `order` · `text` · `group`. For `order` the student taps the choices in the right order and each gets a number 1 · 2 · 3 (tap again to remove, "답안 초기화" to clear); the answer string is the same as before. Question, choice and group ids (`q1`, `a`, `g1`) are lower-case letters and digits; once set, do not change them.
6
+ - **In-progress answers are saved automatically (template 1.12.0)**: before the first submission, the student screen saves the answers being worked on to the viewer's own store (`app.kvstore`, key `quiz.draft`, shape `{ v: 1, savedAt, answers: { questionId: { type, value } } }`) 0.8 s after the last change and right away when the page is hidden, and fills them back when the student reopens. Answers of a question that was removed or changed type, and removed choices or groups, are dropped. Once a submission exists the submitted answer wins: the kit fills it, the draft is deleted and no longer saved. Tutors (read-only) and the editor preview do not save. Failures are silent (one console line). Keep this when changing `screens/learn.js`; do not add another save of the same answers.
6
7
  - Student answer (`pattern`, the default): **one string**, `id=answer` per question joined by `;` in question order: `q1=b;q2=a,d;q3=c,a,b;q4=weight;q5=g1:a|g2:b,c`. Multiple choice lists choice ids **sorted**, order lists them in slot order, group lists `group:choices(sorted)` in group order joined by `|`, and a text answer is trimmed and sent **as typed with only `%` → `%25` and `;` → `%3B`** when the settings carry `"answerFormat": 2` (template 1.10.0 and later saves it), or `encodeURIComponent`-encoded when the tag is missing (quizzes saved by 1.9.x or earlier). Both decode with one `decodeURIComponent`.
7
8
  - Answers: the instructor picks the answer in each question card of the edit screen. Single and multiple choice mark it in the option rows (a "정답" radio or checkbox per option), group sorting picks each option's group in its row, order uses a separate "정답" section, and text questions pick an answer mode ("정답 입력 방식"): "직접 입력" (one allowed answer per line, any one is correct) or "정규 표현식" (a regex such as `[Aa]pples?|사과`, with a "채점 테스트" box that grades a sample answer the way the server does). A leading `^` · trailing `$` are dropped and a leading `(?i)` becomes `(?i:…)`; syntax the server (Python `regex`) and the browser read differently is blocked on save (`;`, flags in the middle, back-references, named groups, `[^]`, `\p{…}`, `\b`, `\Z` and similar; the list is in ADR 0013). Saving builds one regex and checks it, and blocks the save with the question number when an answer is missing, points at a deleted choice, or the regex does not match the answers back or still matches a changed answer. The quiz grades with `pattern` or `partial_pattern` (no hand-written regex for the whole quiz, only per text question; the author picks the type on the edit screen with the "부분 채점 허용" switch shown from two questions, a new quiz is `pattern`); its completion policy is `on_graded` (set by the publish skill with the answers, or picked in the '설정' panel at the top of the LXP edit page); with `on_submit` the server does not grade (`is_correct: null`, the kit shows "제출했어요."). `pattern` compares the whole answer at once, so **everything must match for 100**.
8
9
  - **Partial score per question (`partial_pattern`, 2 ②)**: ask the person which one they want ("모두 맞혀야 100점" or "문항별 부분 점수"). For partial scores, write into `.ecdk/settings.json` both the public `"gradingType": "partial_pattern"` (the student screen cannot see `grading`, so this tells it to submit an array) and `grading` `{ "type": "partial_pattern", "answer_key": ["^q1=b$", "^q2=a,d$", …], "scores": [60, 40, …] }`, one regex per question in question order, each the same as one `id=answer` piece of the `pattern` regex wrapped in `^…$`. Scores come from the person or the planning material, otherwise the automatic score: every question gets `ceil(100 / questions)` (3 questions → 34 · 34 · 34, the server caps the student's score at 100). Also write `"pointsMode": "custom"` with each question's `"points"` (same values as `scores`), or `"pointsMode": "equal"` for the automatic score. Build the regexes with `core/model.js`, never by hand ([15](15-edit-settings-by-hand.md)), run `ecdk doctor`, then have the person open the edit view and save once ("초안으로 저장") so the edit screen checks every answer. The author can change both on the edit screen: the "부분 채점 허용" switch picks `pattern` or `partial_pattern`, the row under it shows "자동 배점" or "직접 배점" with the total, and each question card has a score field (custom scores must be integers 0–100 summing to at least 100; "동일 점수로 적용하기" goes back to automatic). A quiz saved before keeps its type and scores unless the author changes them. The student answer is then an array `["q1=b", "q2=a,d", …]`, and the student screen marks each question ✓ · ✕ from `answer_correctness` (right after submitting and when reopened); below 100 it shows a box with the score, "아쉬워요!" and a mascot above the submit bar, and with custom scores each question title shows "N점". With `pattern` the score line is hidden: one question shows "오답입니다." in its card, and several questions with any wrong show "틀린 문제가 있습니다. 다시 한번 풀어보세요." above the submit bar. Every question must still be answered before submitting.
@@ -27,6 +27,7 @@ export declare const ErrorCode: Readonly<{
27
27
  ScriptLoadFailed: 'script_load_failed';
28
28
  ScriptNamespaceNotFound: 'script_namespace_not_found';
29
29
  StorageLimitExceeded: 'storage_limit_exceeded';
30
+ RoomFull: 'room_full';
30
31
  }>;
31
32
  export declare class EliceCDKError extends Error {
32
33
  static code: typeof ErrorCode;
@@ -121,10 +122,46 @@ interface Assets {
121
122
 
122
123
  type KvValue = string | number | boolean | Record<string, any>;
123
124
 
125
+ type KvConnection = 'connecting' | 'live' | 'reconnecting' | 'polling' | 'offline';
126
+
127
+ interface KvRoomMember {
128
+ accountId: number;
129
+ joinedAt: number;
130
+ }
131
+
132
+ interface KvRoom {
133
+ readonly name: string;
134
+ readonly accountId: number | null;
135
+ readonly members: readonly KvRoomMember[];
136
+ subscribe(
137
+ listener: (
138
+ event:
139
+ | { type: 'members'; members: KvRoomMember[] }
140
+ | { type: 'message'; message: { accountId: number; t: number; type: string; data: unknown } }
141
+ | { type: 'connection'; state: KvConnection }
142
+ | { type: 'closed'; error: EliceCDKError }
143
+ ) => void
144
+ ): () => void;
145
+ send(type: string, data?: unknown): Promise<{ t: number }>;
146
+ leave(): Promise<void>;
147
+ }
148
+
124
149
  interface Kvstore {
125
150
  get<T extends KvValue = any>(params: { key: string }, init?: RequestInit): Promise<T | null>;
126
151
  post(params: { key: string; value: KvValue }, init?: RequestInit): Promise<void>;
127
152
  delete(key: string, init?: RequestInit): Promise<void>;
153
+ readPublic(params?: {
154
+ accountIds?: number[];
155
+ }): Promise<Array<{ accountId: number; value: unknown; updatedAt: string }>>;
156
+ subscribe(
157
+ listener: (
158
+ event:
159
+ | { type: 'changed'; accountId: number }
160
+ | { type: 'sync' }
161
+ | { type: 'connection'; state: KvConnection }
162
+ ) => void
163
+ ): () => void;
164
+ joinRoom(name: string): Promise<KvRoom>;
128
165
  }
129
166
 
130
167
  /** Learner files (provisional SDK API, waits for the SDK owners' agreement) */
@@ -25,7 +25,10 @@
25
25
  * 그 밖(서버 없음)은 이 페이지 메모리에만 둔다 (blob: 주소, 새로고침 · 다른 화면에서는 없음)
26
26
  * - 동영상 플레이어: videoPlayerUrl · accessToken은 null (ecdk dev나 LXP에서 시험)
27
27
  * - kvstore: settings처럼 이 브라우저에 보는 사람의 값을 최상위 key별로 둔다.
28
- * 튜터는 쓸 수 없다(read_only_mode). 크기 · 쓰기 횟수 제한은 없음
28
+ * 튜터는 쓸 수 없다(read_only_mode). 크기 · 쓰기 횟수 제한은 없음.
29
+ * readPublic · subscribe · joinRoom은 실제 SDK 편집기 미리보기처럼 이 사람 혼자(account 0):
30
+ * readPublic은 자기 public 줄 하나, subscribe는 바로 live + sync · 자기 public 쓰기에 changed,
31
+ * 방은 혼자이고 보낸 메시지가 자기에게 돌아온다 (이름 · 크기 검사는 같음, 튜터는 방에 못 들어감)
29
32
  * - mlapi (mlapi.fetch): mlapi를 부르지 않고, ecdk dev처럼 서버 오류 모양의 503 SERVICE_UNAVAILABLE
30
33
  * (reason ai_not_configured)로 답한다 (AI 호출은 LXP에서 시험)
31
34
  * - 시나리오: 주소에 ?mock=session_expired | rate_limited | request_failed | external_service_error
@@ -56,6 +59,7 @@ export const ErrorCode = Object.freeze({
56
59
  ScriptLoadFailed: 'script_load_failed',
57
60
  ScriptNamespaceNotFound: 'script_namespace_not_found',
58
61
  StorageLimitExceeded: 'storage_limit_exceeded',
62
+ RoomFull: 'room_full',
59
63
  });
60
64
 
61
65
  export class EliceCDKError extends Error {
@@ -619,6 +623,16 @@ export class MockEliceCDK {
619
623
  },
620
624
  });
621
625
  // The viewer's values in this material, kept in the browser store ('kv': { key: value })
626
+ // Live calls (readPublic · subscribe · joinRoom): the viewer alone as account 0, like the SDK's editor preview
627
+ const kvListeners = new Set();
628
+ let publicUpdatedAt = new Date(0).toISOString();
629
+ const notifyPublic = key => {
630
+ if (key !== 'public' && !key.startsWith('public.')) return;
631
+ publicUpdatedAt = new Date().toISOString();
632
+ for (const listener of [...kvListeners]) listener({ type: 'changed', accountId: 0 });
633
+ };
634
+ let joinedRoom = null;
635
+ const ROOM_NAME = /^[a-z0-9_-]{1,32}$/;
622
636
  this.#kvstore = Object.freeze({
623
637
  get: async ({ key }) => {
624
638
  this.#assertReady();
@@ -633,6 +647,7 @@ export class MockEliceCDK {
633
647
  throw new EliceCDKError(ErrorCode.ReadOnlyMode, 'A tutor cannot save values (mock).');
634
648
  await this.#delay();
635
649
  this.#store.set('kv', kvWrite(this.#store.get('kv', null), key, value));
650
+ notifyPublic(key);
636
651
  },
637
652
  delete: async key => {
638
653
  this.#assertReady();
@@ -646,6 +661,79 @@ export class MockEliceCDK {
646
661
  const parent = kvRead(next, parts.join('.'));
647
662
  if (parent && typeof parent === 'object' && !Array.isArray(parent)) delete parent[last];
648
663
  this.#store.set('kv', next);
664
+ notifyPublic(key);
665
+ },
666
+ readPublic: async ({ accountIds } = {}) => {
667
+ this.#assertReady();
668
+ if (accountIds !== undefined && (!Array.isArray(accountIds) || accountIds.length > 100))
669
+ throw new EliceCDKError(ErrorCode.InvalidParam, '`accountIds` must be at most 100 account ids (mock).');
670
+ await this.#delay();
671
+ const value = kvRead(this.#store.get('kv', null) ?? {}, 'public');
672
+ if (value == null || (accountIds && !accountIds.includes(0))) return [];
673
+ return [{ accountId: 0, value, updatedAt: publicUpdatedAt }];
674
+ },
675
+ subscribe: listener => {
676
+ this.#assertReady();
677
+ if (typeof listener !== 'function')
678
+ throw new EliceCDKError(ErrorCode.InvalidParam, 'The listener must be a function (mock).');
679
+ kvListeners.add(listener);
680
+ queueMicrotask(() => {
681
+ if (!kvListeners.has(listener)) return;
682
+ listener({ type: 'connection', state: 'live' });
683
+ listener({ type: 'sync' });
684
+ });
685
+ return () => kvListeners.delete(listener);
686
+ },
687
+ joinRoom: async name => {
688
+ this.#assertReady();
689
+ if (typeof name !== 'string' || !ROOM_NAME.test(name))
690
+ throw new EliceCDKError(ErrorCode.InvalidParam, `Invalid room name "${name}" (mock).`);
691
+ if (this.#viewer === 'tutor')
692
+ throw new EliceCDKError(ErrorCode.ReadOnlyMode, 'A tutor cannot join a room (mock).');
693
+ if (joinedRoom) {
694
+ if (joinedRoom.name === name) return joinedRoom;
695
+ throw new EliceCDKError(ErrorCode.InvalidParam, `Already in room "${joinedRoom.name}" (mock).`);
696
+ }
697
+ await this.#delay();
698
+ const listeners = new Set();
699
+ const members = [{ accountId: 0, joinedAt: Date.now() }];
700
+ let left = false;
701
+ const room = Object.freeze({
702
+ name,
703
+ accountId: 0,
704
+ members,
705
+ subscribe: listener => {
706
+ listeners.add(listener);
707
+ queueMicrotask(() => {
708
+ if (!listeners.has(listener)) return;
709
+ listener({ type: 'connection', state: left ? 'offline' : 'live' });
710
+ listener({ type: 'members', members: [...members] });
711
+ });
712
+ return () => listeners.delete(listener);
713
+ },
714
+ send: async (type, data = null) => {
715
+ this.#assertReady();
716
+ if (left) throw new EliceCDKError(ErrorCode.InvalidParam, `Room "${name}" was left (mock).`);
717
+ if (typeof type !== 'string' || type.length < 1 || type.length > 32)
718
+ throw new EliceCDKError(ErrorCode.InvalidParam, 'The message type must be 1 to 32 characters (mock).');
719
+ const bytes = new TextEncoder().encode(JSON.stringify({ type, data }) ?? '').length;
720
+ if (bytes > 1024)
721
+ throw new EliceCDKError(ErrorCode.InvalidParam, `The message is ${bytes} bytes; at most 1024 (mock).`);
722
+ const t = Date.now();
723
+ queueMicrotask(() => {
724
+ for (const listener of [...listeners])
725
+ listener({ type: 'message', message: { accountId: 0, t, type, data } });
726
+ });
727
+ return { t };
728
+ },
729
+ leave: async () => {
730
+ left = true;
731
+ listeners.clear();
732
+ if (joinedRoom === room) joinedRoom = null;
733
+ },
734
+ });
735
+ joinedRoom = room;
736
+ return room;
649
737
  },
650
738
  });
651
739
 
@@ -297,6 +297,11 @@ export interface ContentApp<C = Record<string, unknown>> {
297
297
  navigation: Navigation | null;
298
298
  isLocal: boolean;
299
299
  sdkKind: 'real' | 'mock' | 'custom';
300
+ /**
301
+ * 키트가 쓰는 SDK 객체 그대로 (real이면 @eliceio/cdk의 EliceCDK, mock이면 흉내 SDK). 키트가 감싸지 않은 기능에만:
302
+ * kvstore(예: 보드 템플릿 core/board.js의 `createBoard(app.sdk)`가 씀) 등. 제출 · 저장은 키트(useSubmit · useSave)로
303
+ */
304
+ readonly sdk: any;
300
305
  /** 자료 id (토큰 · 주소가 아님) */
301
306
  materialId: string | null;
302
307
  account: { anonymousId: string; fullname: string | null } | null;
@@ -100,6 +100,8 @@ const MESSAGES = {
100
100
  not_initialized: '아직 준비되지 않았습니다.',
101
101
  // 저장 칸 (app.kvstore): 학습자료 × 계정 한도(서버)를 넘음 · 저장 이름(key) 형식이 틀림
102
102
  storage_limit_exceeded: '저장할 내용이 너무 커서 저장하지 못했어요.',
103
+ // 방 (sdk.kvstore.joinRoom): 8명이 이미 들어가 있음
104
+ room_full: '방이 가득 찼어요 (최대 8명). 다른 방을 골라 주세요.',
103
105
  invalid_param: '저장 이름이 올바르지 않습니다.',
104
106
  // 키트만의 코드: Elice 비디오 플레이어 (app.videoPlayer)
105
107
  video_player_unavailable: '동영상을 불러올 수 없습니다.',
@@ -521,6 +523,11 @@ export async function start(options) {
521
523
  isLocal: launch.local,
522
524
  /** 쓰고 있는 SDK: 'real' | 'mock' | 'custom' */
523
525
  sdkKind: kind,
526
+ /**
527
+ * 키트가 쓰는 SDK 객체 그대로 (real이면 @eliceio/cdk의 EliceCDK, mock이면 흉내 SDK). 키트가 감싸지 않은 기능에만 쓴다:
528
+ * kvstore(예: 보드 템플릿 core/board.js의 `createBoard(app.sdk)`가 씀) 등. 제출 · 저장은 키트(useSubmit · useSave)로
529
+ */
530
+ sdk,
524
531
  /** 자료 id (토큰 · 주소가 아님. 이 브라우저에 남기는 값의 키 등에) */
525
532
  materialId: sdk.metadata?.materialId ?? null,
526
533
  /** 보는 사람 { anonymousId, fullname } */