@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
@@ -0,0 +1,182 @@
1
+ import { build } from 'esbuild';
2
+ import 'fflate';
3
+ import { resolveRef } from '../rules/path.js';
4
+ import { classifyRef } from '../rules/refs.js';
5
+ import { rules } from '../rules/spec.js';
6
+
7
+ /**
8
+ * LXP는 자료를 origin이 `null`인 sandbox iframe(`allow-scripts`)에서 열고, 자료 파일 서버는
9
+ * `Access-Control-Allow-Origin`을 주지 않는다. 그래서 CORS 모드로 받는 요청이 모두 막힌다:
10
+ * `<script type="module" src>` · 그 안의 `import` · `import()` · `fetch('content.json')`.
11
+ * (일반 `<script src>` · `<link rel="stylesheet">` · `<img>`는 CORS를 쓰지 않아 그대로 된다.)
12
+ *
13
+ * build는 zip에 넣기 전에 HTML마다:
14
+ * - `<script type="module" src="상대경로">`를 esbuild로 하나로 묶어 `<script type="module">` 본문으로 넣는다
15
+ * (zip 안 파일만 묶음. `import.meta.url`은 원래 파일 주소로 바꿔 상대경로 계산이 그대로 맞게).
16
+ * - zip 안 JSON(metadata.json 제외)을 페이지에 넣고 `fetch`가 그 주소를 받으면 넣어 둔 내용을 돌려준다.
17
+ * 원본 JS · JSON 파일은 zip에 그대로 둔다 (`ecdk dev` · 다른 참조용).
18
+ */
19
+ const encoder = new TextEncoder();
20
+ const decoder = new TextDecoder();
21
+ const MODULE_SCRIPT = /<script\b([^>]*)>\s*<\/script\s*>/gi;
22
+ /** build가 묶어 넣은 모듈 스크립트 표시 (검사가 본문을 건너뜀) */
23
+ const BUNDLE_ATTR = 'data-ecdk-bundle';
24
+ function attr(attrs, name) {
25
+ const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(attrs);
26
+ return m ? m[1] ?? m[2] ?? m[3] : undefined;
27
+ }
28
+ /** HTML 안에 넣어도 태그가 끝나지 않게 */
29
+ const escapeInline = code => code.replace(/<\/(script)/gi, '<\\/$1');
30
+ /** zip 안 파일만 읽는 esbuild 플러그인. zip 밖(외부 주소 · 패키지 이름)은 오류 */
31
+ /** 페이지 폴더에서 zip 최상위로 올라가는 ../ (하위 폴더 페이지는 깊이만큼) */
32
+ const upFrom = page => '../'.repeat(page.split('/').length - 1);
33
+ function zipFiles(byPath, page) {
34
+ return {
35
+ name: 'ecdk-zip',
36
+ setup(b) {
37
+ b.onResolve({
38
+ filter: /.*/
39
+ }, args => {
40
+ // 진입 파일은 zip 경로로 넘긴다. 실행 폴더에 같은 이름의 파일이 있으면 esbuild가 앞에 ./를 붙여 넘기므로 뗀다
41
+ if (args.kind === 'entry-point') {
42
+ const path = args.path.replace(/^\.\//, '');
43
+ if (!byPath.has(path)) return {
44
+ errors: [{
45
+ text: `파일이 없습니다: ${args.path}`
46
+ }]
47
+ };
48
+ return {
49
+ path,
50
+ namespace: 'zip'
51
+ };
52
+ }
53
+ if (classifyRef(args.path) !== 'local') return {
54
+ errors: [{
55
+ text: `zip 안 파일만 묶을 수 있습니다: ${args.path}`
56
+ }]
57
+ };
58
+ const path = resolveRef(args.importer, args.path.replace(/[?#].*$/, ''));
59
+ if (path === null || !byPath.has(path)) return {
60
+ errors: [{
61
+ text: `파일이 없습니다: ${args.path} (${args.importer}에서)`
62
+ }]
63
+ };
64
+ return {
65
+ path,
66
+ namespace: 'zip'
67
+ };
68
+ });
69
+ b.onLoad({
70
+ filter: /.*/,
71
+ namespace: 'zip'
72
+ }, args => {
73
+ const file = byPath.get(args.path);
74
+ // 빈 내용으로 묶으면 build는 통과하고 LXP에서 화면이 뜨지 않으므로, 찾지 못하면 오류로 알린다
75
+ if (!file) return {
76
+ errors: [{
77
+ text: `파일이 없습니다: ${args.path}`
78
+ }]
79
+ };
80
+ const text = decoder.decode(file.data);
81
+ // 묶으면 import.meta.url이 페이지 주소가 된다. 원래 파일 주소로 두어 new URL('./x', import.meta.url)이 그대로 맞게.
82
+ // 하위 폴더 페이지는 깊이만큼 올라가고, <base href>와 상관없도록 페이지 주소(location.href) 기준으로
83
+ const contents = text.replaceAll('import.meta.url', `new URL(${JSON.stringify(upFrom(page) + args.path)}, location.href).href`);
84
+ return {
85
+ contents,
86
+ loader: /\.json$/i.test(args.path) ? 'json' : 'js'
87
+ };
88
+ });
89
+ }
90
+ };
91
+ }
92
+ async function bundle(entry, page, byPath, opts) {
93
+ const r = await build({
94
+ entryPoints: [entry],
95
+ ...(opts.workingDir ? {
96
+ absWorkingDir: opts.workingDir
97
+ } : {}),
98
+ // minify를 켜면 실제로 실행되는 묶음 코드를 줄인다 (원본 JS는 이제 실행되지 않음)
99
+ minify: opts.minify === true,
100
+ bundle: true,
101
+ format: 'esm',
102
+ target: 'es2022',
103
+ write: false,
104
+ logLevel: 'silent',
105
+ plugins: [zipFiles(byPath, page)]
106
+ }).catch(e => {
107
+ throw new Error(`${entry}를 묶지 못했습니다: ${e.errors?.[0]?.text ?? e.message ?? 'esbuild 오류'}. LXP에서는 모듈 스크립트를 따로 받을 수 없어 build가 HTML 안에 묶어 넣습니다.`);
108
+ });
109
+ return r.outputFiles[0]?.text ?? '';
110
+ }
111
+ /** zip 안 JSON을 넣어 두고, 그 주소를 fetch하면 넣어 둔 내용을 돌려준다 */
112
+ function jsonPrelude(files, page) {
113
+ // zip 최상위 기준 경로 앞에 페이지 깊이만큼 ../를 붙여, 실행할 때 페이지 주소(location.href)로 풀어 비교한다.
114
+ // fetch 인자는 브라우저처럼 document.baseURI로 푼다
115
+ const up = upFrom(page);
116
+ const data = {};
117
+ for (const f of files) {
118
+ if (!/\.json$/i.test(f.path) || f.path === rules.manifest.file) continue;
119
+ try {
120
+ data[up + f.path] = JSON.parse(decoder.decode(f.data));
121
+ } catch {
122
+ // 형식이 틀린 JSON은 넣지 않는다 (검사가 알려 줌)
123
+ }
124
+ }
125
+ if (Object.keys(data).length === 0) return '';
126
+ const json = escapeInline(JSON.stringify(data));
127
+ return `<script>(()=>{const d=${json},b=document.baseURI,m=new Map(Object.entries(d).map(([k,v])=>[new URL(k,location.href).href,v])),f=window.fetch.bind(window);window.fetch=(i,o)=>{try{const u=new URL(typeof i==='string'||i instanceof URL?i:i.url,b).href.replace(/[?#].*$/,'');if(m.has(u)&&(!o||!o.method||o.method.toUpperCase()==='GET'))return Promise.resolve(new Response(JSON.stringify(m.get(u)),{headers:{'Content-Type':'application/json'}}))}catch{}return f(i,o)}})();</script>`;
128
+ }
129
+ /** HTML의 모듈 스크립트(src)를 묶어 본문으로 넣는다. 바뀐 파일만 새로 만들어 돌려준다 */
130
+ async function inlineModuleScripts(files, /** esbuild 작업 폴더 (기본: 실행 폴더). 테스트에서 프로젝트 폴더 안 실행을 흉내 낼 때 */
131
+ opts = {}) {
132
+ const byPath = new Map(files.map(f => [f.path, f]));
133
+ const pages = [];
134
+ const out = [];
135
+ for (const f of files) {
136
+ if (!/\.html?$/i.test(f.path)) {
137
+ out.push(f);
138
+ continue;
139
+ }
140
+ const html = decoder.decode(f.data);
141
+ // 주석 안의 스크립트(<!-- <script type="module" src="old.js"> -->)는 실행되지 않으므로 묶지 않는다
142
+ const comments = [...html.matchAll(/<!--[\s\S]*?-->/g)].map(c => [c.index, c.index + c[0].length]);
143
+ const inComment = at => comments.some(([from, to]) => at > from && at < to);
144
+ const scripts = [...html.matchAll(MODULE_SCRIPT)].filter(m => {
145
+ if (inComment(m.index)) return false;
146
+ const a = m[1] ?? '';
147
+ const src = attr(a, 'src');
148
+ return attr(a, 'type')?.toLowerCase() === 'module' && src && classifyRef(src) === 'local';
149
+ });
150
+ if (scripts.length === 0) {
151
+ out.push(f);
152
+ continue;
153
+ }
154
+ let next = '';
155
+ let last = 0;
156
+ for (const [i, m] of scripts.entries()) {
157
+ const src = attr(m[1] ?? '', 'src') ?? '';
158
+ const entry = resolveRef(f.path, src.replace(/[?#].*$/, ''));
159
+ if (entry === null || !byPath.has(entry)) throw new Error(`${f.path}의 모듈 스크립트 파일이 없습니다: ${src}`);
160
+ const code = await bundle(entry, f.path, byPath, opts);
161
+ next += html.slice(last, m.index);
162
+ if (i === 0) next += jsonPrelude(files, f.path);
163
+ // data-ecdk-bundle: 원본(ecdk-ignore 주석 포함)을 이미 검사했으니 zip 검사에서 이 본문은 다시 보지 않는다
164
+ next += `<script type="module" ${BUNDLE_ATTR}="${entry}">\n${escapeInline(code)}</script>`;
165
+ last = (m.index ?? 0) + m[0].length;
166
+ }
167
+ next += html.slice(last);
168
+ pages.push(f.path);
169
+ out.push({
170
+ ...f,
171
+ data: encoder.encode(next)
172
+ });
173
+ }
174
+ return {
175
+ files: out,
176
+ report: {
177
+ pages
178
+ }
179
+ };
180
+ }
181
+
182
+ export { BUNDLE_ATTR, inlineModuleScripts };
@@ -0,0 +1,25 @@
1
+ /** 패키지 루트의 templates/ (es/core/와 src/core/ 모두 두 단계 위) */
2
+ export declare const TEMPLATE_ROOT: string;
3
+ /**
4
+ * 템플릿 한 개의 정보 (`templates/<이름>/template.json`). 템플릿마다 버전을 따로 올린다 (CLI 버전과 별개).
5
+ * 화면 구성 · 완료 정책은 template.json에 다시 적지 않고 템플릿의 elice.config.json을 그대로 읽는다 (한 곳만 고치게).
6
+ */
7
+ export interface TemplateInfo {
8
+ name: string;
9
+ version: string;
10
+ title: string;
11
+ description: string;
12
+ /** 템플릿 elice.config.json의 screens 키 */
13
+ screens: string[];
14
+ /** 템플릿 elice.config.json의 completionPolicies (첫 값이 기본, 하나면 고정) */
15
+ completionPolicies?: string[] | undefined;
16
+ }
17
+ /** 이 CLI가 가진 템플릿 (이름 순, 공통 폴더 `_shared` 제외) */
18
+ export declare function listTemplates(root?: string): TemplateInfo[];
19
+ /** 검사 규칙 build.template-unknown에 넘길 { 이름: 버전 } */
20
+ export declare function knownTemplates(root?: string): Record<string, string>;
21
+ /** "quiz@1.0.0" → { name, version } (버전이 없으면 undefined) */
22
+ export declare function parseTemplateRef(ref: string): {
23
+ name: string;
24
+ version?: string | undefined;
25
+ };
@@ -0,0 +1,41 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ /** 패키지 루트의 templates/ (es/core/와 src/core/ 모두 두 단계 위) */
6
+ const TEMPLATE_ROOT = fileURLToPath(new URL('../../templates', import.meta.url));
7
+ /** 이 CLI가 가진 템플릿 (이름 순, 공통 폴더 `_shared` 제외) */
8
+ function listTemplates(root = TEMPLATE_ROOT) {
9
+ return readdirSync(root, {
10
+ withFileTypes: true
11
+ }).filter(d => d.isDirectory() && !d.name.startsWith('_')).map(d => {
12
+ const meta = JSON.parse(readFileSync(join(root, d.name, 'template.json'), 'utf8'));
13
+ const config = JSON.parse(readFileSync(join(root, d.name, 'elice.config.json'), 'utf8'));
14
+ return {
15
+ name: meta.name,
16
+ version: meta.version,
17
+ title: meta.title,
18
+ description: meta.description,
19
+ screens: Object.keys(config.screens ?? {}),
20
+ ...(config.completionPolicies ? {
21
+ completionPolicies: config.completionPolicies
22
+ } : {})
23
+ };
24
+ }).sort((a, b) => a.name.localeCompare(b.name));
25
+ }
26
+ /** 검사 규칙 build.template-unknown에 넘길 { 이름: 버전 } */
27
+ function knownTemplates(root = TEMPLATE_ROOT) {
28
+ return Object.fromEntries(listTemplates(root).map(t => [t.name, t.version]));
29
+ }
30
+ /** "quiz@1.0.0" → { name, version } (버전이 없으면 undefined) */
31
+ function parseTemplateRef(ref) {
32
+ const at = ref.lastIndexOf('@');
33
+ return at > 0 ? {
34
+ name: ref.slice(0, at),
35
+ version: ref.slice(at + 1)
36
+ } : {
37
+ name: ref
38
+ };
39
+ }
40
+
41
+ export { TEMPLATE_ROOT, knownTemplates, listTemplates, parseTemplateRef };
@@ -1,15 +1,22 @@
1
- import type { GradingConfig } from '../core/config.js';
2
- /** 제출 응답 `{ is_correct, score }` (서버 설계 v25). 채점하지 않는 유형은 둘 다 null */
1
+ import type { LocalGrading } from '../core/config.js';
2
+ /** 제출 응답 `{ is_correct, score }` (서버 설계 v25). 채점하지 않는 정책은 둘 다 null */
3
3
  export interface GradeResult {
4
4
  isCorrect: boolean | null;
5
5
  score: number | null;
6
6
  }
7
7
  /** dev가 rubric(AI) 채점을 흉내 낼 때 돌려주는 점수. 서버는 요청 안에서 채점한다 */
8
8
  export declare const RUBRIC_DEV_SCORE = 80;
9
+ /** 정답 비교에 쓰는 답 문자열: 문자열은 앞뒤 공백을 자르고, 그 밖은 JSON으로 */
10
+ export declare const answerText: (answer: unknown) => string;
11
+ /** pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞는지. 정규식이 틀리거나 없으면 오답 */
12
+ export declare function matchesPattern(answerKey: unknown, answer: unknown): boolean;
9
13
  /**
10
- * elice-material `grading` 흉내 (서버 설계 v25). 채점은 모두 요청 안에서 끝난다 (rubric 포함).
11
- * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이고,
12
- * pattern exact는 서버처럼 답 전체를 한 번에 비교한다 (부분 점수 없음).
13
- * manual · none 등 자동 채점이 아닌 유형은 `{ isCorrect: null, score: null }`.
14
+ * elice-material 채점 흉내 (ADR 0009: 완료 정책 → 채점 방식 → 점수). 채점은 모두 요청 안에서 끝난다.
15
+ * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다.
16
+ * - on_access: 열면 완료, 제출은 점수 없음 `{ null, null }`
17
+ * - on_submit: 제출하면 100
18
+ * - on_graded + pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
19
+ * - on_graded + rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음, G136)
20
+ * - on_graded인데 grading.json이 없으면 채점할 수 없어 `{ null, null }`
14
21
  */
15
- export declare function grade(grading: GradingConfig | undefined, answer: unknown): GradeResult;
22
+ export declare function grade(local: LocalGrading | undefined, answer: unknown): GradeResult;
package/es/dev/grading.js CHANGED
@@ -1,30 +1,44 @@
1
1
  /** dev가 rubric(AI) 채점을 흉내 낼 때 돌려주는 점수. 서버는 요청 안에서 채점한다 */
2
2
  const RUBRIC_DEV_SCORE = 80;
3
- const normalize = v => typeof v === 'string' ? v.trim().toLowerCase() : Array.isArray(v) ? v.map(normalize).sort() : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, normalize(v[k])])) : v;
3
+ /** 정답 비교에 쓰는 답 문자열: 문자열은 앞뒤 공백을 자르고, 그 밖은 JSON으로 */
4
+ const answerText = answer => typeof answer === 'string' ? answer.trim() : JSON.stringify(answer ?? null);
5
+ /** pattern: 정답 정규식(문자열 하나)이 답 문자열 전체와 맞는지. 정규식이 틀리거나 없으면 오답 */
6
+ function matchesPattern(answerKey, answer) {
7
+ if (typeof answerKey !== 'string') return false;
8
+ try {
9
+ return new RegExp(`^(?:${answerKey})$`).test(answerText(answer));
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
4
14
  /**
5
- * elice-material `grading` 흉내 (서버 설계 v25). 채점은 모두 요청 안에서 끝난다 (rubric 포함).
6
- * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이고,
7
- * pattern exact는 서버처럼 답 전체를 한 번에 비교한다 (부분 점수 없음).
8
- * manual · none 등 자동 채점이 아닌 유형은 `{ isCorrect: null, score: null }`.
15
+ * elice-material 채점 흉내 (ADR 0009: 완료 정책 → 채점 방식 → 점수). 채점은 모두 요청 안에서 끝난다.
16
+ * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다.
17
+ * - on_access: 열면 완료, 제출은 점수 없음 `{ null, null }`
18
+ * - on_submit: 제출하면 100
19
+ * - on_graded + pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
20
+ * - on_graded + rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음, G136)
21
+ * - on_graded인데 grading.json이 없으면 채점할 수 없어 `{ null, null }`
9
22
  */
10
- function grade(grading, answer) {
11
- const type = grading?.type ?? 'on_submit';
12
- if (type === 'on_access') return {
23
+ function grade(local, answer) {
24
+ const policy = local?.completion_policy ?? 'on_submit';
25
+ if (policy === 'on_access') return {
13
26
  isCorrect: null,
14
27
  score: null
15
28
  };
16
- if (type === 'on_submit') return {
29
+ if (policy === 'on_submit') return {
17
30
  isCorrect: true,
18
31
  score: 100
19
32
  };
20
- if (type === 'pattern') {
21
- const ok = grading?.match === 'regex' ? new RegExp(String(grading.answer_key)).test(String(answer)) : JSON.stringify(normalize(answer)) === JSON.stringify(normalize(grading?.answer_key));
33
+ const grading = local?.grading;
34
+ if (grading?.type === 'pattern') {
35
+ const ok = matchesPattern(grading.answer_key, answer);
22
36
  return {
23
37
  isCorrect: ok,
24
38
  score: ok ? 100 : 0
25
39
  };
26
40
  }
27
- if (type === 'rubric') return {
41
+ if (grading?.type === 'rubric') return {
28
42
  isCorrect: true,
29
43
  score: RUBRIC_DEV_SCORE
30
44
  };
@@ -34,4 +48,4 @@ function grade(grading, answer) {
34
48
  };
35
49
  }
36
50
 
37
- export { RUBRIC_DEV_SCORE, grade };
51
+ export { RUBRIC_DEV_SCORE, answerText, grade, matchesPattern };
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * LXP 학습 · 편집 페이지 흉내. 보기를 바꾸고 콘텐츠를 sandbox iframe으로 띄우며,
3
- * @eliceio/cdk가 보내는 postMessage(settings-change · navigate-*)를 받아 처리한다
3
+ * @eliceio/cdk가 보내는 postMessage(settings-saved · navigate-*)를 받아 처리한다
4
4
  */
5
5
  export declare function hostPage(opts: {
6
6
  title: string;
@@ -2,7 +2,7 @@ import { DEV_MATERIAL_ID } from './mock-api.js';
2
2
 
3
3
  /**
4
4
  * LXP 학습 · 편집 페이지 흉내. 보기를 바꾸고 콘텐츠를 sandbox iframe으로 띄우며,
5
- * @eliceio/cdk가 보내는 postMessage(settings-change · navigate-*)를 받아 처리한다
5
+ * @eliceio/cdk가 보내는 postMessage(settings-saved · navigate-*)를 받아 처리한다
6
6
  */
7
7
  function hostPage(opts) {
8
8
  return `<!doctype html>
@@ -51,7 +51,6 @@ function hostPage(opts) {
51
51
  <button data-w="100%" aria-pressed="true">데스크톱</button><button data-w="720px">태블릿</button><button data-w="360px">모바일</button>
52
52
  </div>
53
53
  <span class="sep"></span>
54
- <button id="save" hidden disabled title="편집 화면이 saveSettings()로 넘긴 설정을 자료에 저장합니다">저장</button>
55
54
  <button id="reset" title="제출 기록 · 점수 · 완료, 편집 화면에서 저장한 내용을 지우고 처음 들어온 상태로 다시 엽니다">처음 상태로</button>
56
55
  <span class="sep"></span>
57
56
  <details id="sdk-tools">
@@ -62,6 +61,10 @@ function hostPage(opts) {
62
61
  <label><input type="checkbox" id="has-prev" checked>이전 차시 있음</label>
63
62
  <label><input type="checkbox" id="has-next" checked>다음 차시 있음</label>
64
63
  </div>
64
+ <div class="tool" role="group" aria-label="저장 전 편집 화면" title="LXP 편집 페이지에서 zip을 올리고 아직 저장하지 않은 상태의 편집 화면처럼 토큰 없이 엽니다. 저장하면 SDK가 draft_not_saved로 거절합니다">
65
+ <b>저장 전 편집 화면</b> <code>#edit=1</code>
66
+ <button type="button" id="open-edit-draft">열기</button>
67
+ </div>
65
68
  <div class="tool" role="group" aria-label="저장 전 미리보기" title="LXP 편집 페이지의 미리보기처럼 토큰 없이 학생 화면을 엽니다. settings가 비어 content.json 기본 내용으로 뜨고, 제출은 기록되지 않습니다(늘 100점)">
66
69
  <b>저장 전 미리보기</b> <code>#preview=1</code>
67
70
  <button type="button" id="open-preview">열기</button>
@@ -76,27 +79,34 @@ function hostPage(opts) {
76
79
  <script type="module">
77
80
  const MATERIAL_ID = ${JSON.stringify(DEV_MATERIAL_ID)};
78
81
  const SDK_SOURCE = 'eliceio-content-sdk';
79
- // [보기, 이름, 화면, 주소 조각]. token은 흉내 서버가 발급, edit는 운영처럼 토큰 없음.
82
+ // [보기, 이름, 화면, 주소 조각]. token은 흉내 서버가 발급. 내용 편집은 LXP처럼 저장된 버전을 edit 토큰으로 연다
80
83
  const SCENARIOS = [
81
84
  ['student', '학생', 'learn', 'token'],
82
85
  ['tutor', '튜터링', 'learn', 'token'],
83
86
  ['instructor', '교육자 화면', 'instructor', 'token'],
84
- ['edit', '내용 편집', 'edit', 'edit=1'],
87
+ ['edit', '내용 편집', 'edit', 'token'],
88
+ // 완료 정책 화면 (ADR 0009): LXP 설정 탭처럼 edit 토큰 + screen=completionPolicy. screens.completionPolicy를 켠
89
+ // 자료에서만 보인다 (퀴즈처럼 completionPolicies가 하나면 없음). 저장하면 .ecdk/completion.json, 채점 방식 · 답은 내용 편집
90
+ ['completionPolicy', '완료 정책', 'completionPolicy', 'token'],
85
91
  ];
86
92
  // 토큰 없는 미리보기(#preview=1)는 settings가 비고 늘 100점이라 학생 보기와 구분이 안 돼 보기 버튼에서 빼고,
87
93
  // SDK 기능 안의 도구로만 연다 (SDK · 키트는 이 상태를 따로 다룸: isDraftPreview, "기록되지 않음" 안내)
88
94
  const PREVIEW = ['preview', '저장 전 미리보기', 'learn', 'preview=1'];
89
- const scenarioOf = (name) => (name === PREVIEW[0] ? PREVIEW : SCENARIOS.find((s) => s[0] === name));
95
+ // 저장 전 업로드의 편집 화면 (토큰 없음): saveSettings가 draft_not_saved로 거절되는 것을 확인할 때
96
+ const EDIT_DRAFT = ['edit-draft', '저장 전 편집 화면', 'edit', 'edit=1'];
97
+ const TOOLS = [PREVIEW, EDIT_DRAFT];
98
+ const scenarioOf = (name) => TOOLS.find((s) => s[0] === name) ?? SCENARIOS.find((s) => s[0] === name);
99
+ // LXP처럼 material API 주소를 fragment로 넘긴다 (키트는 dev에서 __ECDK_DEV__.api를 먼저 쓴다)
100
+ const BASE_URL = encodeURIComponent(location.origin + '/api');
90
101
  const frame = document.getElementById('content');
91
102
  const previewEl = document.getElementById('open-preview');
92
103
  const scenariosEl = document.getElementById('scenarios');
93
- const saveEl = document.getElementById('save');
104
+ const editDraftEl = document.getElementById('open-edit-draft');
94
105
  const messagesEl = document.getElementById('messages');
95
106
  let state = { kind: 'material', entries: {}, contentBase: '' };
96
107
  // 저장소가 막힌 브라우저에서도 화면이 떠야 하므로 sessionStorage는 모두 try로 감싼다
97
108
  let current = 'student';
98
109
  try { current = sessionStorage.getItem('ecdk-scenario') || 'student'; } catch {}
99
- let pendingSettings = null;
100
110
 
101
111
  function note(line) {
102
112
  const lines = (messagesEl.textContent ? messagesEl.textContent.split('\\n') : []).slice(-4);
@@ -112,24 +122,22 @@ function hostPage(opts) {
112
122
  try { sessionStorage.setItem('ecdk-scenario', scenario); } catch {}
113
123
  for (const b of scenariosEl.children) b.setAttribute('aria-pressed', String(b.dataset.scenario === scenario));
114
124
  previewEl.setAttribute('aria-pressed', String(scenario === PREVIEW[0]));
125
+ editDraftEl.setAttribute('aria-pressed', String(scenario === EDIT_DRAFT[0]));
115
126
  const [, label, screen, fragment] = scenarioOf(scenario);
116
127
  const entry = entryOf(screen);
117
- pendingSettings = null;
118
- saveEl.hidden = scenario !== 'edit';
119
- saveEl.disabled = true;
120
128
  // 같은 파일이면 해시만 바뀌어 다시 로드되지 않으므로 매번 쿼리를 바꾼다
121
129
  const url = state.contentBase + entry + '?ecdk=' + Date.now();
122
130
  if (fragment === 'token') {
123
131
  const { token } = await (await fetch('/__ecdk/token?scenario=' + scenario)).json();
124
- frame.src = url + '#token=' + token;
132
+ frame.src = url + '#token=' + token + '&baseUrl=' + BASE_URL + (screen === 'completionPolicy' ? '&screen=completionPolicy' : '');
125
133
  } else {
126
- frame.src = url + '#' + fragment;
134
+ frame.src = url + '#' + fragment + '&baseUrl=' + BASE_URL;
127
135
  }
128
136
  document.getElementById('hint').textContent =
129
- (state.kind === 'description' ? '문제 설명 · ' : '') + entry + ' · ' + (scenario === PREVIEW[0] ? label : scenario);
137
+ (state.kind === 'description' ? '문제 설명 · ' : '') + entry + ' · ' + (TOOLS.some((t) => t[0] === scenario) ? label : scenario);
130
138
  }
131
139
 
132
- // 화면(learn · instructor · edit)은 검사기가 kindModes로 이미 걸러 state.entries에 켠 것만 온다.
140
+ // 화면(learn · instructor · edit · completionPolicy)은 검사기가 kindModes로 이미 걸러 state.entries에 켠 것만 온다.
133
141
  // 문제 설명에는 학생 보기만 둔다: 다른 보기가 있는지는 서버 · LXP와 아직 정하지 않았다 (progress G81)
134
142
  const available = (s) => entryOf(s[2]) && (state.kind !== 'description' || s[0] === 'student');
135
143
  function renderScenarios() {
@@ -139,7 +147,9 @@ function hostPage(opts) {
139
147
  b.onclick = () => open(scenario);
140
148
  return b;
141
149
  }));
142
- const keep = current === PREVIEW[0] ? available(PREVIEW) : SCENARIOS.some((s) => s[0] === current && available(s));
150
+ const tool = TOOLS.find((t) => t[0] === current);
151
+ const keep = tool ? available(tool) : SCENARIOS.some((s) => s[0] === current && available(s));
152
+ editDraftEl.disabled = !available(EDIT_DRAFT);
143
153
  if (!keep) current = 'student';
144
154
  }
145
155
 
@@ -156,11 +166,13 @@ function hostPage(opts) {
156
166
  if (!data || typeof data !== 'object' || data.source !== SDK_SOURCE) return;
157
167
  const payload = data.payload || {};
158
168
  switch (data.type) {
159
- case 'settings-change':
160
- if (current !== 'edit' || !payload.settings || typeof payload.settings !== 'object') return;
161
- pendingSettings = payload.settings;
162
- saveEl.disabled = false;
163
- note('settings-change: ' + JSON.stringify(pendingSettings) + ' (저장을 누르면 자료에 저장)');
169
+ // 편집 화면의 saveSettings 결과. 저장은 콘텐츠가 edit 토큰으로 이미 했고, 편집 페이지는 표시만 한다
170
+ case 'settings-saved':
171
+ note(payload.status === 'saved'
172
+ ? (current === 'completionPolicy'
173
+ ? 'settings-saved: 완료 정책을 저장했습니다 (.ecdk/completion.json). 학생 보기가 이 정책으로 완료 · 채점합니다'
174
+ : 'settings-saved: 저장했습니다. 다른 보기에서 material.settings로 받습니다 (채점 방식 · 답은 grading.json)')
175
+ : 'settings-saved: 저장 실패 (' + payload.code + ')');
164
176
  return;
165
177
  case 'navigate-prev':
166
178
  note('navigate-prev: 이전 차시로 이동 (dev는 이동하지 않음)');
@@ -192,19 +204,6 @@ function hostPage(opts) {
192
204
  }
193
205
  });
194
206
 
195
- // 편집 페이지의 자료 저장: 마지막으로 받은 settings를 edit 토큰으로 PATCH
196
- saveEl.onclick = async () => {
197
- if (!pendingSettings) return;
198
- const { token } = await (await fetch('/__ecdk/token?scenario=edit')).json();
199
- const res = await fetch('/api/materials/' + MATERIAL_ID, {
200
- method: 'PATCH',
201
- headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
202
- body: JSON.stringify({ settings: pendingSettings }),
203
- });
204
- note(res.ok ? '저장했습니다. 다른 보기에서 material.settings로 받습니다' : '저장 실패 (' + res.status + ')');
205
- if (res.ok) saveEl.disabled = true;
206
- };
207
-
208
207
  for (const b of document.querySelectorAll('[data-w]')) b.onclick = () => {
209
208
  for (const x of document.querySelectorAll('[data-w]')) x.setAttribute('aria-pressed', String(x === b));
210
209
  frame.style.setProperty('--w', b.dataset.w);
@@ -222,6 +221,7 @@ function hostPage(opts) {
222
221
  toolsEl.querySelector('summary').focus();
223
222
  });
224
223
  previewEl.onclick = () => { toolsEl.open = false; open(PREVIEW[0]); };
224
+ editDraftEl.onclick = () => { toolsEl.open = false; open(EDIT_DRAFT[0]); };
225
225
  document.getElementById('reset').onclick = async () => { await fetch('/__ecdk/reset', { method: 'POST' }); open(current); };
226
226
 
227
227
  state = await (await fetch('/__ecdk/state')).json();
@@ -1,5 +1,5 @@
1
+ import { type CompletionPolicy, type GradingConfig, type LocalGrading } from '../core/config.js';
1
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { GradingConfig } from '../core/config.js';
3
3
  /**
4
4
  * elice-material API 흉내 (서버 설계 v25, @eliceio/cdk 1.x가 부르는 것만).
5
5
  * 응답은 elib 형식 `{ data, meta }`, 필드는 snake_case. 오류는 `{ data: null, meta: { error } }`.
@@ -20,9 +20,14 @@ export type MaterialViewer = 'student' | 'instructor' | 'tutor';
20
20
  /**
21
21
  * dev 호스트 화면의 보기 (dev 전용). 토큰은 scope + viewer로 바뀐다.
22
22
  * - student · instructor · tutor: `#token=…` (scope learn)
23
- * - edit: 토큰 없이 `#edit=1`. edit 토큰은 호스트의 "저장" 버튼이 PATCH할 때만 쓴다
23
+ * - edit: `#token=…` (scope edit). LXP 편집 페이지처럼 저장된 버전의 편집 화면을 edit 토큰으로 열고,
24
+ * 콘텐츠의 `saveSettings`가 이 토큰으로 바로 PATCH한다 (토큰 없는 `#edit=1` draft는 저장할 수 없음)
25
+ * - completionPolicy: `#token=…&screen=completionPolicy` (scope edit). 완료 정책 화면 (ADR 0009). SDK
26
+ * `saveCompletionPolicy`가 보낸 `PATCH { completion_policy }`를 `.ecdk/completion.json`에 쓴다 (운영은 material_version)
27
+ * 편집 화면의 `saveSettings`가 보낸 `settings.grading`({ type: pattern | rubric })은 프로젝트의 grading.json에 쓰고,
28
+ * 학생 · 튜터 · 교육자(learn scope) 응답에는 서버처럼 `grading`을 빼고 준다
24
29
  */
25
- export type DevScenario = 'student' | 'instructor' | 'tutor' | 'edit';
30
+ export type DevScenario = 'student' | 'instructor' | 'tutor' | 'edit' | 'completionPolicy';
26
31
  /** 토큰을 발급하는 보기 */
27
32
  export type TokenScenario = DevScenario;
28
33
  export declare const TOKEN_SCENARIOS: Readonly<Record<DevScenario, {
@@ -47,6 +52,8 @@ interface Result {
47
52
  }
48
53
  export interface MockState {
49
54
  settings: Record<string, unknown>;
55
+ /** 저장할 때마다 올라가는 버전 번호. 응답의 `current_version.id`는 `dev-{n}` */
56
+ version: number;
50
57
  submissions: Submission[];
51
58
  /** 계정별 결과. 자료당 하나이고 버전이 바뀌어도 지우지 않는다 */
52
59
  results: Map<number, Result>;
@@ -56,8 +63,17 @@ export interface MockState {
56
63
  export declare const createState: () => MockState;
57
64
  export interface MockApiOptions {
58
65
  state: MockState;
59
- getGrading: () => GradingConfig | undefined;
66
+ /** 채점에 쓰는 값 (로컬 완료 정책 + grading.json) */
67
+ getGrading: () => LocalGrading | undefined;
68
+ /** grading.json에 저장된 채점 설정 (없으면 null). edit 범위 응답의 `settings.grading` */
69
+ getSavedGrading?: () => GradingConfig | null;
70
+ /** 편집 화면이 저장한 `settings.grading`을 grading.json에 쓴다 */
71
+ writeGradingFile?: (grading: GradingConfig) => Promise<void>;
60
72
  getEntries: () => Record<string, string>;
73
+ /** metadata completionPolicies (서버가 metadata를 그대로 돌려준다고 보고 응답에 넣는다, G132) */
74
+ getCompletionPolicies?: () => string[];
75
+ /** 완료 정책 화면이 저장한 completion_policy를 .ecdk/completion.json에 쓴다 */
76
+ saveCompletionPolicy?: (policy: CompletionPolicy) => Promise<void>;
61
77
  onEvent?: (message: string) => void;
62
78
  }
63
79
  /** `/api` 아래 요청을 처리한다 */