@eliceio/cdk-cli 0.0.0-stage → 0.1.0-alpha.1

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 (128) hide show
  1. package/README.md +511 -2
  2. package/es/bin/index.d.ts +2 -0
  3. package/es/bin/index.js +10 -0
  4. package/es/cli.d.ts +5 -0
  5. package/es/cli.js +171 -0
  6. package/es/commands/build/index.d.ts +27 -0
  7. package/es/commands/build/index.js +154 -0
  8. package/es/commands/check/index.d.ts +9 -0
  9. package/es/commands/check/index.js +31 -0
  10. package/es/commands/create/index.d.ts +8 -0
  11. package/es/commands/create/index.js +22 -0
  12. package/es/commands/create/scaffold.d.ts +24 -0
  13. package/es/commands/create/scaffold.js +82 -0
  14. package/es/commands/dev/index.d.ts +6 -0
  15. package/es/commands/dev/index.js +40 -0
  16. package/es/commands/doctor/index.d.ts +33 -0
  17. package/es/commands/doctor/index.js +230 -0
  18. package/es/core/collect.d.ts +21 -0
  19. package/es/core/collect.js +89 -0
  20. package/es/core/config.d.ts +55 -0
  21. package/es/core/config.js +109 -0
  22. package/es/core/manifest.d.ts +15 -0
  23. package/es/core/manifest.js +43 -0
  24. package/es/core/minify.d.ts +18 -0
  25. package/es/core/minify.js +93 -0
  26. package/es/core/prepare.d.ts +12 -0
  27. package/es/core/prepare.js +86 -0
  28. package/es/core/protocol.d.ts +2 -0
  29. package/es/core/protocol.js +4 -0
  30. package/es/core/zip.d.ts +4 -0
  31. package/es/core/zip.js +17 -0
  32. package/es/dev/grading.d.ts +15 -0
  33. package/es/dev/grading.js +37 -0
  34. package/es/dev/host-page.d.ts +7 -0
  35. package/es/dev/host-page.js +240 -0
  36. package/es/dev/inject.d.ts +8 -0
  37. package/es/dev/inject.js +38 -0
  38. package/es/dev/mock-api.d.ts +65 -0
  39. package/es/dev/mock-api.js +269 -0
  40. package/es/dev/server.d.ts +24 -0
  41. package/es/dev/server.js +294 -0
  42. package/es/engines/static/index.d.ts +3 -0
  43. package/es/engines/static/index.js +11 -0
  44. package/es/engines/types.d.ts +12 -0
  45. package/es/engines/vite/index.d.ts +2 -0
  46. package/es/engines/vite/index.js +4 -0
  47. package/es/index.d.ts +2 -0
  48. package/es/index.js +2 -0
  49. package/es/rules/check.d.ts +2 -0
  50. package/es/rules/check.js +209 -0
  51. package/es/rules/index.d.ts +8 -0
  52. package/es/rules/index.js +7 -0
  53. package/es/rules/manifest.d.ts +39 -0
  54. package/es/rules/manifest.js +168 -0
  55. package/es/rules/node.d.ts +11 -0
  56. package/es/rules/node.js +87 -0
  57. package/es/rules/path.d.ts +7 -0
  58. package/es/rules/path.js +35 -0
  59. package/es/rules/refs.d.ts +19 -0
  60. package/es/rules/refs.js +111 -0
  61. package/es/rules/skip.d.ts +12 -0
  62. package/es/rules/skip.js +55 -0
  63. package/es/rules/spec.d.ts +3 -0
  64. package/es/rules/spec.js +6 -0
  65. package/es/rules/types.d.ts +138 -0
  66. package/es/rules/unused.d.ts +7 -0
  67. package/es/rules/unused.js +21 -0
  68. package/es/rules/zip.d.ts +13 -0
  69. package/es/rules/zip.js +45 -0
  70. package/es/rules.json.js +3 -0
  71. package/es/types.d.ts +4 -0
  72. package/es/version.d.ts +1 -0
  73. package/es/version.js +3 -0
  74. package/package.json +48 -3
  75. package/rules.json +555 -0
  76. package/templates/_shared/lib/cdk-mock.d.ts +94 -0
  77. package/templates/_shared/lib/cdk-mock.js +429 -0
  78. package/templates/_shared/lib/cdk.js +3 -0
  79. package/templates/_shared/lib/elice-content.css +252 -0
  80. package/templates/_shared/lib/elice-content.d.ts +121 -0
  81. package/templates/_shared/lib/elice-content.js +541 -0
  82. package/templates/_shared/lib/elice-tokens.css +446 -0
  83. package/templates/blank/README.md +64 -0
  84. package/templates/blank/content.json +4 -0
  85. package/templates/blank/edit.html +15 -0
  86. package/templates/blank/elice.config.json +12 -0
  87. package/templates/blank/gitignore +3 -0
  88. package/templates/blank/index.html +15 -0
  89. package/templates/blank/instructor.html +15 -0
  90. package/templates/blank/screens/edit.js +21 -0
  91. package/templates/blank/screens/instructor.js +9 -0
  92. package/templates/blank/screens/learn.js +19 -0
  93. package/templates/blank/styles.css +1 -0
  94. package/templates/quiz/README.md +108 -0
  95. package/templates/quiz/content.json +81 -0
  96. package/templates/quiz/core/behaviors.d.ts +59 -0
  97. package/templates/quiz/core/behaviors.js +309 -0
  98. package/templates/quiz/core/dom.d.ts +13 -0
  99. package/templates/quiz/core/dom.js +83 -0
  100. package/templates/quiz/core/editor.d.ts +48 -0
  101. package/templates/quiz/core/editor.js +206 -0
  102. package/templates/quiz/core/markdown.d.ts +2 -0
  103. package/templates/quiz/core/markdown.js +84 -0
  104. package/templates/quiz/core/model.d.ts +20 -0
  105. package/templates/quiz/core/model.js +203 -0
  106. package/templates/quiz/edit.html +17 -0
  107. package/templates/quiz/elice.config.json +14 -0
  108. package/templates/quiz/gitignore +3 -0
  109. package/templates/quiz/grading.json +13 -0
  110. package/templates/quiz/index.html +17 -0
  111. package/templates/quiz/instructor.html +17 -0
  112. package/templates/quiz/screens/edit.js +139 -0
  113. package/templates/quiz/screens/instructor.js +27 -0
  114. package/templates/quiz/screens/learn.js +50 -0
  115. package/templates/quiz/styles.css +510 -0
  116. package/templates/quiz/ui/templates/choice.js +22 -0
  117. package/templates/quiz/ui/templates/edit.d.ts +14 -0
  118. package/templates/quiz/ui/templates/edit.js +187 -0
  119. package/templates/quiz/ui/templates/group.js +47 -0
  120. package/templates/quiz/ui/templates/index.d.ts +5 -0
  121. package/templates/quiz/ui/templates/index.js +17 -0
  122. package/templates/quiz/ui/templates/order.js +35 -0
  123. package/templates/quiz/ui/templates/page.js +29 -0
  124. package/templates/quiz/ui/templates/question.js +28 -0
  125. package/templates/quiz/ui/templates/text.js +16 -0
  126. package/templates/quiz/ui/texts.d.ts +3 -0
  127. package/templates/quiz/ui/texts.js +128 -0
  128. package/templates/quiz/ui/theme.css +50 -0
@@ -0,0 +1,93 @@
1
+ import { transform } from 'esbuild';
2
+
3
+ /**
4
+ * `elice.config.json`의 `"minify": true`일 때 zip에 넣기 전에 줄인다 (용량 줄이기).
5
+ * 파일 단위 변환(번들 아님)이라 경로 · import · 파일 구성은 그대로다.
6
+ *
7
+ * - JS(.js · .mjs): 공백 · 주석 제거, 이름 줄이기. ES 모듈의 import/export와 top-level await는 그대로.
8
+ * - CSS: 공백 · 주석 제거.
9
+ * - JSON: 공백 제거 (형식이 틀리면 그대로 둠, 검사가 알려 줌). metadata.json은 사람이 보도록 그대로.
10
+ * - HTML · 이미지 등은 그대로.
11
+ * - sourcemap: 줄인 JS · CSS 옆에 `<파일>.map`을 두고 끝에 sourceMappingURL을 단다 (원본 내용 포함).
12
+ * 이미 줄여 둔 파일(minify로 10%도 안 줄어듦, 예: lib/cdk.js)은 .map을 만들지 않는다.
13
+ *
14
+ * 검사는 minify 전 원본으로 한다 (`ecdk-ignore` 주석 · 원본 줄 번호). build 참고.
15
+ */
16
+ const encoder = new TextEncoder();
17
+ const decoder = new TextDecoder();
18
+ const KEEP = new Set(['metadata.json']);
19
+ async function minifyFiles(files, {
20
+ sourcemap = false
21
+ } = {}) {
22
+ let count = 0;
23
+ let before = 0;
24
+ let after = 0;
25
+ const maps = [];
26
+ const out = await Promise.all(files.map(async f => {
27
+ if (KEEP.has(f.path)) return f;
28
+ const loader = /\.m?js$/i.test(f.path) ? 'js' : /\.css$/i.test(f.path) ? 'css' : null;
29
+ const isJson = /\.json$/i.test(f.path);
30
+ if (!loader && !isJson) return f;
31
+ const text = decoder.decode(f.data);
32
+ let next;
33
+ if (isJson) {
34
+ try {
35
+ next = JSON.stringify(JSON.parse(text));
36
+ } catch {
37
+ return f;
38
+ }
39
+ } else if (loader) {
40
+ const name = f.path.split('/').pop() ?? f.path;
41
+ try {
42
+ const r = await transform(text, {
43
+ loader,
44
+ minify: true,
45
+ target: 'es2022',
46
+ ...(sourcemap ? {
47
+ sourcemap: 'external',
48
+ sourcefile: name
49
+ } : {})
50
+ });
51
+ next = r.code;
52
+ // 이미 줄여 둔 파일(묶어 넣은 SDK 등)은 .map이 줄인 코드를 다시 가리킬 뿐이라 용량만 늘린다
53
+ const alreadyMin = encoder.encode(next).byteLength > f.data.byteLength * 0.9;
54
+ if (sourcemap && r.map && !alreadyMin) {
55
+ next += loader === 'css' ? `\n/*# sourceMappingURL=${name}.map */\n` : `\n//# sourceMappingURL=${name}.map\n`;
56
+ maps.push({
57
+ path: `${f.path}.map`,
58
+ data: encoder.encode(r.map)
59
+ });
60
+ }
61
+ } catch (e) {
62
+ const detail = e.errors?.[0];
63
+ throw new Error(`minify 실패: ${f.path}${detail?.location ? `:${detail.location.line}` : ''} ${detail?.text ?? e.message}. 문법을 확인하거나 elice.config.json의 minify를 끄세요.`);
64
+ }
65
+ } else return f;
66
+ const data = encoder.encode(next);
67
+ if (data.byteLength >= f.data.byteLength && !sourcemap) return f;
68
+ count += 1;
69
+ before += f.data.byteLength;
70
+ after += data.byteLength;
71
+ return {
72
+ path: f.path,
73
+ data
74
+ };
75
+ }));
76
+ const mapBytes = maps.reduce((s, m) => s + m.data.byteLength, 0);
77
+ return {
78
+ files: [...out, ...maps],
79
+ report: {
80
+ files: count,
81
+ before,
82
+ after,
83
+ ...(sourcemap ? {
84
+ maps: {
85
+ files: maps.length,
86
+ bytes: mapBytes
87
+ }
88
+ } : {})
89
+ }
90
+ };
91
+ }
92
+
93
+ export { minifyFiles };
@@ -0,0 +1,12 @@
1
+ import { type Excluded, type SourceFile } from './collect.js';
2
+ import type { ContentConfig } from './config.js';
3
+ export interface PreparedContent {
4
+ srcDir: string;
5
+ outDir: string;
6
+ engine: string;
7
+ /** zip에 들어갈 파일 전부 (metadata.json 포함) */
8
+ files: SourceFile[];
9
+ excluded: Excluded[];
10
+ }
11
+ /** build와 doctor가 같은 결과를 보도록: 수집 → 엔진 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다. */
12
+ export declare function prepareContent(projectDir: string, config: ContentConfig): Promise<PreparedContent>;
@@ -0,0 +1,86 @@
1
+ import { resolve, relative, sep, isAbsolute } from 'node:path';
2
+ import { staticEngine } from '../engines/static/index.js';
3
+ import 'fflate';
4
+ import { serializeManifest } from '../rules/manifest.js';
5
+ import { rules } from '../rules/spec.js';
6
+ import { collectSources } from './collect.js';
7
+ import { createBuildInfo } from './manifest.js';
8
+
9
+ const isInside = (parent, child) => {
10
+ const rel = relative(parent, child);
11
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
12
+ };
13
+ /** build와 doctor가 같은 결과를 보도록: 수집 → 엔진 → metadata.json(화면 + 빌드 정보). 디스크에는 쓰지 않는다. */
14
+ async function prepareContent(projectDir, config) {
15
+ const srcDir = resolve(projectDir, config.root);
16
+ const outDir = resolve(projectDir, config.outDir);
17
+ // build는 <outDir>/content/를 지우고 다시 만든다: 프로젝트 밖이나 프로젝트 폴더 자체를 가리키면 다른 데이터를 지울 수 있다
18
+ if (!isInside(resolve(projectDir), outDir)) throw new Error(`outDir는 프로젝트 폴더 안이어야 합니다 (예: "dist"): ${config.outDir}. 밖을 가리키면 그 아래 content/를 지울 수 있어 막습니다.`);
19
+ if (outDir === srcDir || isInside(outDir, srcDir)) throw new Error('outDir는 root와 같거나 root를 품을 수 없습니다.');
20
+ const skipDirs = isInside(srcDir, outDir) ? [relative(srcDir, outDir).split(sep).join('/')] : [];
21
+ const {
22
+ files: sources,
23
+ excluded
24
+ } = await collectSources(srcDir, {
25
+ skipDirs,
26
+ exclude: config.exclude,
27
+ projectRoot: srcDir === resolve(projectDir)
28
+ });
29
+ const engine = staticEngine;
30
+ const files = await engine.build({
31
+ srcDir,
32
+ files: sources
33
+ });
34
+ // metadata.json (zip 최상위): 설정의 kind · screens로 만들고, 없으면 원본 것에 build만 채우고, 둘 다 없으면 학생 화면만
35
+ const build = createBuildInfo(engine.name, {
36
+ template: config.template,
37
+ files
38
+ });
39
+ // 학습 참고 내용: 원본 최상위 .txt 파일을 zip에 그대로 두고, metadata.json commentary에 이름만 적는다
40
+ const commentaryName = (config.commentary ?? rules.manifest.commentaryFile).replace(/^\.\//, '');
41
+ const hasCommentary = files.some(f => f.path === commentaryName);
42
+ if (config.commentary !== undefined && !hasCommentary) throw new Error(`학습 참고 내용 파일이 원본 최상위에 없습니다: ${config.commentary} (elice.config.json commentary)`);
43
+ const commentary = hasCommentary ? commentaryName : undefined;
44
+ const authored = files.find(f => f.path === rules.manifest.file);
45
+ const fromConfig = config.screens ? 'screens' : config.kind ? 'kind' : config.commentary !== undefined ? 'commentary' : null;
46
+ if (authored && fromConfig) throw new Error(`원본에 ${rules.manifest.file}이 있고 ${fromConfig}도 있습니다. 둘 중 하나만 써 주세요.`);
47
+ if (authored) {
48
+ // 형식이 틀리면 그대로 두고 검사가 알려 준다. 맞으면 다른 필드는 지키고 build만 바꾼다
49
+ let raw = null;
50
+ try {
51
+ raw = JSON.parse(new TextDecoder().decode(authored.data));
52
+ } catch {
53
+ raw = null;
54
+ }
55
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) authored.data = new TextEncoder().encode(`${JSON.stringify({
56
+ ...raw,
57
+ build
58
+ }, null, 2)}\n`);
59
+ } else {
60
+ // 자료 본문은 채점 유형이 반드시 있다 (문제 설명은 채점하지 않음)
61
+ if ((config.kind ?? rules.manifest.defaultKind) !== 'description' && !config.gradingTypes) throw new Error(`elice.config.json에 이 자료가 지원하는 채점 유형을 적어 주세요: "gradingTypes": [${rules.manifest.gradingTypes.map(t => `"${t}"`).join(', ')}] 중 하나 이상. 보기만 하는 자료는 ["on_access"].`);
62
+ const entries = config.screens ?? {
63
+ learn: rules.manifest.defaultEntry
64
+ };
65
+ files.push({
66
+ path: rules.manifest.file,
67
+ data: new TextEncoder().encode(serializeManifest({
68
+ kind: config.kind,
69
+ entries,
70
+ // 지원 채점 유형만 (교육자가 LXP 채점 설정에서 고르고 정답을 넣음). 문제 설명은 채점하지 않음
71
+ gradingTypes: config.gradingTypes,
72
+ commentary,
73
+ build
74
+ }, rules))
75
+ });
76
+ }
77
+ return {
78
+ srcDir,
79
+ outDir,
80
+ engine: engine.name,
81
+ files,
82
+ excluded
83
+ };
84
+ }
85
+
86
+ export { prepareContent };
@@ -0,0 +1,2 @@
1
+ /** Version of the message protocol between the preview shell and its parent (LXP or the CLI dev host). */
2
+ export declare const PROTOCOL_VERSION = 1;
@@ -0,0 +1,4 @@
1
+ /** Version of the message protocol between the preview shell and its parent (LXP or the CLI dev host). */
2
+ const PROTOCOL_VERSION = 1;
3
+
4
+ export { PROTOCOL_VERSION };
@@ -0,0 +1,4 @@
1
+ export declare function createZip(files: {
2
+ path: string;
3
+ data: Uint8Array;
4
+ }[]): Uint8Array;
package/es/core/zip.js ADDED
@@ -0,0 +1,17 @@
1
+ import { zipSync } from 'fflate';
2
+
3
+ /** 파일 시각을 고정하고 이름순으로 넣어 같은 입력이면 같은 zip이 나온다. 이름은 UTF-8 플래그와 함께 저장된다. */
4
+ const FIXED_MTIME = new Date(1980, 0, 1);
5
+ function createZip(files) {
6
+ const entries = {};
7
+ for (const f of [...files].sort((a, b) => a.path < b.path ? -1 : 1)) {
8
+ entries[f.path] = [f.data, {
9
+ mtime: FIXED_MTIME
10
+ }];
11
+ }
12
+ return zipSync(entries, {
13
+ level: 9
14
+ });
15
+ }
16
+
17
+ export { createZip };
@@ -0,0 +1,15 @@
1
+ import type { GradingConfig } from '../core/config.js';
2
+ /** 제출 응답 `{ is_correct, score }` (서버 설계 v25). 채점하지 않는 유형은 둘 다 null */
3
+ export interface GradeResult {
4
+ isCorrect: boolean | null;
5
+ score: number | null;
6
+ }
7
+ /** dev가 rubric(AI) 채점을 흉내 낼 때 돌려주는 점수. 서버는 요청 안에서 채점한다 */
8
+ export declare const RUBRIC_DEV_SCORE = 80;
9
+ /**
10
+ * elice-material `grading` 흉내 (서버 설계 v25). 채점은 모두 요청 안에서 끝난다 (rubric 포함).
11
+ * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이고,
12
+ * pattern exact는 서버처럼 답 전체를 한 번에 비교한다 (부분 점수 없음).
13
+ * manual · none 등 자동 채점이 아닌 유형은 `{ isCorrect: null, score: null }`.
14
+ */
15
+ export declare function grade(grading: GradingConfig | undefined, answer: unknown): GradeResult;
@@ -0,0 +1,37 @@
1
+ /** dev가 rubric(AI) 채점을 흉내 낼 때 돌려주는 점수. 서버는 요청 안에서 채점한다 */
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;
4
+ /**
5
+ * elice-material `grading` 흉내 (서버 설계 v25). 채점은 모두 요청 안에서 끝난다 (rubric 포함).
6
+ * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이고,
7
+ * pattern exact는 서버처럼 답 전체를 한 번에 비교한다 (부분 점수 없음).
8
+ * manual · none 등 자동 채점이 아닌 유형은 `{ isCorrect: null, score: null }`.
9
+ */
10
+ function grade(grading, answer) {
11
+ const type = grading?.type ?? 'on_submit';
12
+ if (type === 'on_access') return {
13
+ isCorrect: null,
14
+ score: null
15
+ };
16
+ if (type === 'on_submit') return {
17
+ isCorrect: true,
18
+ score: 100
19
+ };
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));
22
+ return {
23
+ isCorrect: ok,
24
+ score: ok ? 100 : 0
25
+ };
26
+ }
27
+ if (type === 'rubric') return {
28
+ isCorrect: true,
29
+ score: RUBRIC_DEV_SCORE
30
+ };
31
+ return {
32
+ isCorrect: null,
33
+ score: null
34
+ };
35
+ }
36
+
37
+ export { RUBRIC_DEV_SCORE, grade };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * LXP 학습 · 편집 페이지 흉내. 보기를 바꾸고 콘텐츠를 sandbox iframe으로 띄우며,
3
+ * @eliceio/cdk가 보내는 postMessage(settings-change · navigate-*)를 받아 처리한다
4
+ */
5
+ export declare function hostPage(opts: {
6
+ title: string;
7
+ }): string;
@@ -0,0 +1,240 @@
1
+ import { DEV_MATERIAL_ID } from './mock-api.js';
2
+
3
+ /**
4
+ * LXP 학습 · 편집 페이지 흉내. 보기를 바꾸고 콘텐츠를 sandbox iframe으로 띄우며,
5
+ * @eliceio/cdk가 보내는 postMessage(settings-change · navigate-*)를 받아 처리한다
6
+ */
7
+ function hostPage(opts) {
8
+ return `<!doctype html>
9
+ <html lang="ko">
10
+ <head>
11
+ <meta charset="utf-8">
12
+ <meta name="viewport" content="width=device-width, initial-scale=1">
13
+ <title>ecdk dev · ${opts.title.replace(/</g, '&lt;')}</title>
14
+ <style>
15
+ :root { color-scheme: light; font-family: system-ui, -apple-system, 'Apple SD Gothic Neo', sans-serif; --line: #d8dce5; --accent: #6a3df0; }
16
+ * { box-sizing: border-box; }
17
+ body { margin: 0; height: 100vh; display: grid; grid-template-rows: auto auto auto 1fr; background: #f5f6f9; color: #1b2230; }
18
+ header { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 8px 12px; background: #fff; border-bottom: 1px solid var(--line); font-size: 13px; }
19
+ header b { margin-right: 8px; }
20
+ .group { display: flex; gap: 4px; align-items: center; }
21
+ .sep { width: 1px; height: 20px; background: var(--line); margin: 0 4px; }
22
+ button { font: inherit; padding: 4px 10px; border: 1px solid var(--line); border-radius: 6px; background: #fff; cursor: pointer; }
23
+ button[aria-pressed="true"] { border-color: var(--accent); color: #fff; background: var(--accent); }
24
+ button:disabled { cursor: default; opacity: 0.5; }
25
+ #check { padding: 6px 12px; font-size: 12px; background: #fff; border-bottom: 1px solid var(--line); white-space: pre-wrap; font-family: ui-monospace, Menlo, monospace; }
26
+ #check.fail { background: #fdecea; color: #b3261e; }
27
+ #messages { margin: 0; padding: 4px 12px; font-size: 12px; background: #fafbfc; border-bottom: 1px solid var(--line); font-family: ui-monospace, Menlo, monospace; white-space: pre-wrap; min-height: 1.6em; }
28
+ main { display: flex; justify-content: center; padding: 12px; min-height: 0; }
29
+ iframe { width: 100%; max-width: var(--w, 100%); height: 100%; border: 1px solid var(--line); border-radius: 8px; background: #fff; }
30
+ .muted { color: #5b6577; }
31
+ label { display: inline-flex; gap: 4px; align-items: center; }
32
+ details#sdk-tools { position: relative; }
33
+ details#sdk-tools summary { display: inline-block; cursor: pointer; padding: 4px 10px; border: 1px solid var(--line); border-radius: 6px; list-style: none; user-select: none; }
34
+ details#sdk-tools summary::-webkit-details-marker { display: none; }
35
+ details#sdk-tools summary::before { content: '▸ '; }
36
+ details#sdk-tools[open] summary::before { content: '▾ '; }
37
+ details#sdk-tools[open] summary { border-color: var(--accent); color: var(--accent); }
38
+ .tools { position: absolute; top: calc(100% + 6px); left: 0; z-index: 10; display: grid; gap: 8px; width: max-content; max-width: calc(100vw - 32px); padding: 10px 12px; background: #fff; border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 6px 20px rgba(27, 34, 48, 0.12); }
39
+ .tool { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
40
+ .tool code { font-size: 12px; color: #5b6577; }
41
+ .tool b { margin: 0; }
42
+ [hidden] { display: none !important; }
43
+ </style>
44
+ </head>
45
+ <body>
46
+ <header>
47
+ <b>ecdk dev</b>
48
+ <div class="group" id="scenarios" role="group" aria-label="보기"></div>
49
+ <span class="sep"></span>
50
+ <div class="group" role="group" aria-label="화면 폭">
51
+ <button data-w="100%" aria-pressed="true">데스크톱</button><button data-w="720px">태블릿</button><button data-w="360px">모바일</button>
52
+ </div>
53
+ <span class="sep"></span>
54
+ <button id="save" hidden disabled title="편집 화면이 saveSettings()로 넘긴 설정을 자료에 저장합니다">저장</button>
55
+ <button id="reset" title="제출 기록 · 점수 · 완료, 편집 화면에서 저장한 내용을 지우고 처음 들어온 상태로 다시 엽니다">처음 상태로</button>
56
+ <span class="sep"></span>
57
+ <details id="sdk-tools">
58
+ <summary title="@eliceio/cdk가 LXP에서 받는 값을 바꿔 봅니다">SDK 기능</summary>
59
+ <div class="tools">
60
+ <div class="tool" role="group" aria-label="차시 이동" title="sdk.navigation.getHasPrevious() · getHasNext()가 받는 값. 끄면 첫 차시 · 마지막 차시처럼 동작합니다. previous() · next()는 dev에서 이동하지 않고 아래에 기록만 남깁니다">
61
+ <b>차시 이동</b> <code>sdk.navigation</code>
62
+ <label><input type="checkbox" id="has-prev" checked>이전 차시 있음</label>
63
+ <label><input type="checkbox" id="has-next" checked>다음 차시 있음</label>
64
+ </div>
65
+ <div class="tool" role="group" aria-label="저장 전 미리보기" title="LXP 편집 페이지의 미리보기처럼 토큰 없이 학생 화면을 엽니다. settings가 비어 content.json 기본 내용으로 뜨고, 제출은 기록되지 않습니다(늘 100점)">
66
+ <b>저장 전 미리보기</b> <code>#preview=1</code>
67
+ <button type="button" id="open-preview">열기</button>
68
+ </div>
69
+ </div>
70
+ </details>
71
+ <span class="muted" id="hint"></span>
72
+ </header>
73
+ <div id="check">검사 중…</div>
74
+ <pre id="messages" aria-live="polite"></pre>
75
+ <main><iframe id="content" sandbox="allow-scripts" title="콘텐츠"></iframe></main>
76
+ <script type="module">
77
+ const MATERIAL_ID = ${JSON.stringify(DEV_MATERIAL_ID)};
78
+ const SDK_SOURCE = 'eliceio-content-sdk';
79
+ // [보기, 이름, 화면, 주소 조각]. token은 흉내 서버가 발급, edit는 운영처럼 토큰 없음.
80
+ const SCENARIOS = [
81
+ ['student', '학생', 'learn', 'token'],
82
+ ['tutor', '튜터링', 'learn', 'token'],
83
+ ['instructor', '교육자 화면', 'instructor', 'token'],
84
+ ['edit', '내용 편집', 'edit', 'edit=1'],
85
+ ];
86
+ // 토큰 없는 미리보기(#preview=1)는 settings가 비고 늘 100점이라 학생 보기와 구분이 안 돼 보기 버튼에서 빼고,
87
+ // SDK 기능 안의 도구로만 연다 (SDK · 키트는 이 상태를 따로 다룸: isDraftPreview, "기록되지 않음" 안내)
88
+ const PREVIEW = ['preview', '저장 전 미리보기', 'learn', 'preview=1'];
89
+ const scenarioOf = (name) => (name === PREVIEW[0] ? PREVIEW : SCENARIOS.find((s) => s[0] === name));
90
+ const frame = document.getElementById('content');
91
+ const previewEl = document.getElementById('open-preview');
92
+ const scenariosEl = document.getElementById('scenarios');
93
+ const saveEl = document.getElementById('save');
94
+ const messagesEl = document.getElementById('messages');
95
+ let state = { kind: 'material', entries: {}, contentBase: '' };
96
+ // 저장소가 막힌 브라우저에서도 화면이 떠야 하므로 sessionStorage는 모두 try로 감싼다
97
+ let current = 'student';
98
+ try { current = sessionStorage.getItem('ecdk-scenario') || 'student'; } catch {}
99
+ let pendingSettings = null;
100
+
101
+ function note(line) {
102
+ const lines = (messagesEl.textContent ? messagesEl.textContent.split('\\n') : []).slice(-4);
103
+ lines.push(new Date().toLocaleTimeString() + ' ' + line);
104
+ messagesEl.textContent = lines.join('\\n');
105
+ }
106
+
107
+ // 교육자 화면은 instructor 진입 파일이 없으면 학생 화면을 연다 (@eliceio/cdk resolveScreen과 같음)
108
+ const entryOf = (screen) => state.entries[screen] || (screen === 'instructor' ? state.entries.learn : undefined);
109
+
110
+ async function open(scenario) {
111
+ current = scenario;
112
+ try { sessionStorage.setItem('ecdk-scenario', scenario); } catch {}
113
+ for (const b of scenariosEl.children) b.setAttribute('aria-pressed', String(b.dataset.scenario === scenario));
114
+ previewEl.setAttribute('aria-pressed', String(scenario === PREVIEW[0]));
115
+ const [, label, screen, fragment] = scenarioOf(scenario);
116
+ const entry = entryOf(screen);
117
+ pendingSettings = null;
118
+ saveEl.hidden = scenario !== 'edit';
119
+ saveEl.disabled = true;
120
+ // 같은 파일이면 해시만 바뀌어 다시 로드되지 않으므로 매번 쿼리를 바꾼다
121
+ const url = state.contentBase + entry + '?ecdk=' + Date.now();
122
+ if (fragment === 'token') {
123
+ const { token } = await (await fetch('/__ecdk/token?scenario=' + scenario)).json();
124
+ frame.src = url + '#token=' + token;
125
+ } else {
126
+ frame.src = url + '#' + fragment;
127
+ }
128
+ document.getElementById('hint').textContent =
129
+ (state.kind === 'description' ? '문제 설명 · ' : '') + entry + ' · ' + (scenario === PREVIEW[0] ? label : scenario);
130
+ }
131
+
132
+ // 화면(learn · instructor · edit)은 검사기가 kindModes로 이미 걸러 state.entries에 켠 것만 온다.
133
+ // 문제 설명에는 학생 보기만 둔다: 다른 보기가 있는지는 서버 · LXP와 아직 정하지 않았다 (progress G81)
134
+ const available = (s) => entryOf(s[2]) && (state.kind !== 'description' || s[0] === 'student');
135
+ function renderScenarios() {
136
+ scenariosEl.replaceChildren(...SCENARIOS.filter(available).map(([scenario, label]) => {
137
+ const b = document.createElement('button');
138
+ b.textContent = label; b.dataset.scenario = scenario;
139
+ b.onclick = () => open(scenario);
140
+ return b;
141
+ }));
142
+ const keep = current === PREVIEW[0] ? available(PREVIEW) : SCENARIOS.some((s) => s[0] === current && available(s));
143
+ if (!keep) current = 'student';
144
+ }
145
+
146
+ function renderCheck(c) {
147
+ const el = document.getElementById('check');
148
+ el.className = c.ok ? '' : 'fail';
149
+ el.textContent = c.summary;
150
+ }
151
+
152
+ // @eliceio/cdk → 학습 · 편집 페이지. 보낸 창이 이 iframe이고 source가 SDK인 것만 받는다
153
+ window.addEventListener('message', (event) => {
154
+ if (event.source !== frame.contentWindow) return;
155
+ const data = event.data;
156
+ if (!data || typeof data !== 'object' || data.source !== SDK_SOURCE) return;
157
+ const payload = data.payload || {};
158
+ 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) + ' (저장을 누르면 자료에 저장)');
164
+ return;
165
+ case 'navigate-prev':
166
+ note('navigate-prev: 이전 차시로 이동 (dev는 이동하지 않음)');
167
+ return;
168
+ case 'navigate-next':
169
+ note('navigate-next: 다음 차시로 이동 (dev는 이동하지 않음)');
170
+ return;
171
+ case 'navigate':
172
+ note('navigate: 차시 ' + payload.lecturePageId + '로 이동 (dev는 이동하지 않음)');
173
+ return;
174
+ case 'navigate-state-sync': {
175
+ const reply = {
176
+ source: SDK_SOURCE,
177
+ type: 'navigate-state',
178
+ materialId: data.materialId,
179
+ requestId: data.requestId,
180
+ payload: {
181
+ hasPreviousLecturePage: document.getElementById('has-prev').checked,
182
+ hasNextLecturePage: document.getElementById('has-next').checked,
183
+ },
184
+ };
185
+ // sandbox iframe의 출처는 null이라 '*'로만 보낼 수 있다
186
+ event.source.postMessage(reply, '*');
187
+ note('navigate-state-sync → ' + JSON.stringify(reply.payload));
188
+ return;
189
+ }
190
+ default:
191
+ note('알 수 없는 메시지: ' + data.type);
192
+ }
193
+ });
194
+
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
+ for (const b of document.querySelectorAll('[data-w]')) b.onclick = () => {
209
+ for (const x of document.querySelectorAll('[data-w]')) x.setAttribute('aria-pressed', String(x === b));
210
+ frame.style.setProperty('--w', b.dataset.w);
211
+ };
212
+ // SDK 기능 펼침 상태는 이 탭에서만 기억한다
213
+ const toolsEl = document.getElementById('sdk-tools');
214
+ try { toolsEl.open = sessionStorage.getItem('ecdk-sdk-tools') === '1'; } catch {}
215
+ toolsEl.ontoggle = () => { try { sessionStorage.setItem('ecdk-sdk-tools', toolsEl.open ? '1' : '0'); } catch {} };
216
+ // 드롭다운은 콘텐츠 위에 뜨므로 바깥 클릭 · 콘텐츠(iframe)로 포커스 이동 · Esc로 닫는다
217
+ document.addEventListener('click', (e) => { if (toolsEl.open && !toolsEl.contains(e.target)) toolsEl.open = false; });
218
+ window.addEventListener('blur', () => { if (toolsEl.open && document.activeElement === frame) toolsEl.open = false; });
219
+ document.addEventListener('keydown', (e) => {
220
+ if (e.key !== 'Escape' || !toolsEl.open) return;
221
+ toolsEl.open = false;
222
+ toolsEl.querySelector('summary').focus();
223
+ });
224
+ previewEl.onclick = () => { toolsEl.open = false; open(PREVIEW[0]); };
225
+ document.getElementById('reset').onclick = async () => { await fetch('/__ecdk/reset', { method: 'POST' }); open(current); };
226
+
227
+ state = await (await fetch('/__ecdk/state')).json();
228
+ renderScenarios(); renderCheck(state.check); open(current);
229
+
230
+ const events = new EventSource('/__ecdk/events');
231
+ events.addEventListener('reload', async (e) => {
232
+ state = JSON.parse(e.data);
233
+ renderScenarios(); renderCheck(state.check); open(current);
234
+ });
235
+ </script>
236
+ </body>
237
+ </html>`;
238
+ }
239
+
240
+ export { hostPage };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * dev에서만 콘텐츠 HTML의 <head> 맨 앞에 넣는 스크립트 (zip에는 들어가지 않음).
3
+ * - 키트가 흉내 서버를 쓰도록 API 주소를, 콘텐츠 주소를 직접 열어 mock으로 돌 때 쓸 로컬 채점 설정 주소를 알려 줌 (window.__ECDK_DEV__)
4
+ * - 콘솔 오류 · 처리 안 된 예외 · 불러오지 못한 파일을 터미널로 보냄
5
+ */
6
+ export declare function devScript(hostOrigin: string): string;
7
+ /** <head> 바로 뒤(없으면 맨 앞)에 넣는다. 다른 스크립트보다 먼저 돌아야 오류를 놓치지 않는다 */
8
+ export declare function injectDevScript(html: string, hostOrigin: string): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * dev에서만 콘텐츠 HTML의 <head> 맨 앞에 넣는 스크립트 (zip에는 들어가지 않음).
3
+ * - 키트가 흉내 서버를 쓰도록 API 주소를, 콘텐츠 주소를 직접 열어 mock으로 돌 때 쓸 로컬 채점 설정 주소를 알려 줌 (window.__ECDK_DEV__)
4
+ * - 콘솔 오류 · 처리 안 된 예외 · 불러오지 못한 파일을 터미널로 보냄
5
+ */
6
+ function devScript(hostOrigin) {
7
+ const api = `${hostOrigin}/api`;
8
+ const log = `${hostOrigin}/__ecdk/log`;
9
+ const grading = `${hostOrigin}/__ecdk/grading`;
10
+ return `<script>
11
+ (() => {
12
+ window.__ECDK_DEV__ = { api: ${JSON.stringify(api)}, grading: ${JSON.stringify(grading)} };
13
+ const send = (level, message) => {
14
+ try { fetch(${JSON.stringify(log)}, { method: 'POST', body: JSON.stringify({ level, message: String(message), page: location.pathname.split('/').pop() }) }); } catch (e) {}
15
+ };
16
+ for (const level of ['error', 'warn']) {
17
+ const orig = console[level];
18
+ console[level] = (...args) => { send(level, args.map((a) => (a instanceof Error ? a.stack || a.message : typeof a === 'string' ? a : JSON.stringify(a))).join(' ')); orig.apply(console, args); };
19
+ }
20
+ addEventListener('error', (e) => {
21
+ const t = e.target;
22
+ if (t && t !== window && (t.src || t.href)) send('error', '불러오지 못함: ' + (t.src || t.href));
23
+ else send('error', (e.error && e.error.stack) || e.message);
24
+ }, true);
25
+ addEventListener('unhandledrejection', (e) => send('error', 'Promise 오류: ' + ((e.reason && e.reason.stack) || e.reason)));
26
+ })();
27
+ </script>`;
28
+ }
29
+ /** <head> 바로 뒤(없으면 맨 앞)에 넣는다. 다른 스크립트보다 먼저 돌아야 오류를 놓치지 않는다 */
30
+ function injectDevScript(html, hostOrigin) {
31
+ const script = devScript(hostOrigin);
32
+ const m = html.match(/<head\b[^>]*>/i);
33
+ if (!m || m.index === undefined) return script + html;
34
+ const at = m.index + m[0].length;
35
+ return html.slice(0, at) + script + html.slice(at);
36
+ }
37
+
38
+ export { devScript, injectDevScript };
@@ -0,0 +1,65 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { GradingConfig } from '../core/config.js';
3
+ /**
4
+ * elice-material API 흉내 (서버 설계 v25, @eliceio/cdk 1.x가 부르는 것만).
5
+ * 응답은 elib 형식 `{ data, meta }`, 필드는 snake_case. 오류는 `{ data: null, meta: { error } }`.
6
+ */
7
+ export declare const DEV_MATERIAL_ID = "00000000-0000-4000-8000-0000000000e1";
8
+ export declare const STUDENT: {
9
+ account_id: number;
10
+ anonymous_id: string;
11
+ fullname: string;
12
+ };
13
+ export declare const MANAGER: {
14
+ account_id: number;
15
+ anonymous_id: string;
16
+ fullname: string;
17
+ };
18
+ export type MaterialScope = 'learn' | 'edit';
19
+ export type MaterialViewer = 'student' | 'instructor' | 'tutor';
20
+ /**
21
+ * dev 호스트 화면의 보기 (dev 전용). 토큰은 scope + viewer로 바뀐다.
22
+ * - student · instructor · tutor: `#token=…` (scope learn)
23
+ * - edit: 토큰 없이 `#edit=1`. edit 토큰은 호스트의 "저장" 버튼이 PATCH할 때만 쓴다
24
+ */
25
+ export type DevScenario = 'student' | 'instructor' | 'tutor' | 'edit';
26
+ /** 토큰을 발급하는 보기 */
27
+ export type TokenScenario = DevScenario;
28
+ export declare const TOKEN_SCENARIOS: Readonly<Record<DevScenario, {
29
+ scope: MaterialScope;
30
+ viewer: MaterialViewer;
31
+ }>>;
32
+ export declare const isTokenScenario: (v: unknown) => v is TokenScenario;
33
+ export declare function issueToken(scenario: TokenScenario, ttlSeconds?: number): string;
34
+ interface Submission {
35
+ id: string;
36
+ material_version_id: string;
37
+ account_id: number;
38
+ created_at: string;
39
+ answer: unknown;
40
+ is_correct: boolean | null;
41
+ score: number | null;
42
+ }
43
+ interface Result {
44
+ score: number | null;
45
+ submit_count: number;
46
+ completed_at: string | null;
47
+ }
48
+ export interface MockState {
49
+ settings: Record<string, unknown>;
50
+ submissions: Submission[];
51
+ /** 계정별 결과. 자료당 하나이고 버전이 바뀌어도 지우지 않는다 */
52
+ results: Map<number, Result>;
53
+ /** 계정별 최근 1분 제출 시각 (rate limit) */
54
+ recent: Map<number, number[]>;
55
+ }
56
+ export declare const createState: () => MockState;
57
+ export interface MockApiOptions {
58
+ state: MockState;
59
+ getGrading: () => GradingConfig | undefined;
60
+ getEntries: () => Record<string, string>;
61
+ onEvent?: (message: string) => void;
62
+ }
63
+ /** `/api` 아래 요청을 처리한다 */
64
+ export declare function handleMockApi(req: IncomingMessage, res: ServerResponse, path: string, opts: MockApiOptions): Promise<void>;
65
+ export {};