@eliceio/cdk-cli 1.5.4 → 1.6.0-entryqa.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 (70) hide show
  1. package/README.md +31 -29
  2. package/es/commands/create/index.js +1 -0
  3. package/es/commands/create/scaffold.d.ts +1 -1
  4. package/es/commands/create/scaffold.js +1 -1
  5. package/es/core/config.d.ts +61 -2
  6. package/es/core/config.js +309 -3
  7. package/es/dev/grading.d.ts +31 -2
  8. package/es/dev/grading.js +68 -1
  9. package/es/dev/mock-api.d.ts +3 -1
  10. package/es/dev/mock-api.js +34 -4
  11. package/es/dev/server.js +5 -4
  12. package/es/rules/answers.d.ts +1 -0
  13. package/es/rules/answers.js +3 -0
  14. package/es/rules/check.js +8 -1
  15. package/es/rules/csp.d.ts +7 -0
  16. package/es/rules/csp.js +24 -3
  17. package/es/rules/index.d.ts +1 -1
  18. package/es/rules/index.js +1 -1
  19. package/es/rules/types.d.ts +4 -3
  20. package/es/rules.json.js +1 -1
  21. package/package.json +2 -2
  22. package/rules.json +5 -4
  23. package/skills/_shared/references/02-design-the-material.md +1 -0
  24. package/skills/_shared/references/05-screen-code.md +1 -0
  25. package/templates/_shared/lib/cdk-mock.d.ts +33 -2
  26. package/templates/_shared/lib/cdk-mock.js +171 -5
  27. package/templates/_shared/lib/elice-content.d.ts +38 -0
  28. package/templates/_shared/lib/elice-content.js +85 -2
  29. package/templates/blank/template.json +1 -1
  30. package/templates/document/template.json +1 -1
  31. package/templates/entry/README.md +118 -0
  32. package/templates/entry/commentary.txt +2 -0
  33. package/templates/entry/core/autosave.d.ts +13 -0
  34. package/templates/entry/core/autosave.js +69 -0
  35. package/templates/entry/core/default-project.d.ts +2 -0
  36. package/templates/entry/core/default-project.js +139 -0
  37. package/templates/entry/core/dom.d.ts +13 -0
  38. package/templates/entry/core/dom.js +83 -0
  39. package/templates/entry/core/grading.d.ts +51 -0
  40. package/templates/entry/core/grading.js +125 -0
  41. package/templates/entry/core/pack.d.ts +12 -0
  42. package/templates/entry/core/pack.js +71 -0
  43. package/templates/entry/core/settings.d.ts +33 -0
  44. package/templates/entry/core/settings.js +79 -0
  45. package/templates/entry/core/workspace.d.ts +40 -0
  46. package/templates/entry/core/workspace.js +320 -0
  47. package/templates/entry/docs/storage.md +44 -0
  48. package/templates/entry/edit.html +17 -0
  49. package/templates/entry/gitignore +4 -0
  50. package/templates/entry/index.html +17 -0
  51. package/templates/entry/metadata.json +9 -0
  52. package/templates/entry/package.json +13 -0
  53. package/templates/entry/screens/edit/panels/answer-project.js +15 -0
  54. package/templates/entry/screens/edit/panels/grading.d.ts +18 -0
  55. package/templates/entry/screens/edit/panels/grading.js +516 -0
  56. package/templates/entry/screens/edit/panels/index.js +25 -0
  57. package/templates/entry/screens/edit/panels/preference.js +38 -0
  58. package/templates/entry/screens/edit/panels/project-panel.js +97 -0
  59. package/templates/entry/screens/edit/panels/start-project.js +6 -0
  60. package/templates/entry/screens/edit.js +263 -0
  61. package/templates/entry/screens/learn.js +255 -0
  62. package/templates/entry/styles.css +872 -0
  63. package/templates/entry/template.json +6 -0
  64. package/templates/entry/ui/templates/page.js +81 -0
  65. package/templates/entry/ui/texts.d.ts +3 -0
  66. package/templates/entry/ui/texts.js +164 -0
  67. package/templates/entry/ui/theme.css +17 -0
  68. package/templates/quiz/template.json +1 -1
  69. package/templates/steps/template.json +1 -1
  70. package/templates/video/template.json +1 -1
@@ -0,0 +1,69 @@
1
+ // 자동 저장: 바뀌었다는 신호(schedule)를 delayMs 동안 모았다가 한 번 저장합니다 (디바운스).
2
+ // 저장하는 동안 또 바뀌면 끝난 뒤 한 번 더 저장합니다. 상태가 바뀔 때마다 onState를 부릅니다.
3
+ // 'idle' 아직 바뀐 것 없음 · 'pending' 저장 기다리는 중 · 'saving' 저장 중 · 'saved' 저장됨 · 'error' 저장 실패
4
+
5
+ /**
6
+ * @param {{
7
+ * save: () => Promise<void>,
8
+ * delayMs?: number,
9
+ * onState?: (state: 'idle' | 'pending' | 'saving' | 'saved' | 'error', info: { error?: unknown, at?: Date }) => void,
10
+ * }} options
11
+ */
12
+ export function createAutosave({ save, delayMs = 2000, onState = () => {} }) {
13
+ let state = 'idle';
14
+ let timer = null;
15
+ let running = null;
16
+ let again = false;
17
+ const set = (next, info = {}) => {
18
+ state = next;
19
+ onState(next, info);
20
+ };
21
+
22
+ async function run() {
23
+ if (running) {
24
+ again = true;
25
+ return running;
26
+ }
27
+ clearTimeout(timer);
28
+ timer = null;
29
+ set('saving');
30
+ running = (async () => {
31
+ try {
32
+ await save();
33
+ set('saved', { at: new Date() });
34
+ } catch (error) {
35
+ set('error', { error });
36
+ } finally {
37
+ running = null;
38
+ }
39
+ if (again) {
40
+ again = false;
41
+ await run();
42
+ }
43
+ })();
44
+ return running;
45
+ }
46
+
47
+ return {
48
+ get state() {
49
+ return state;
50
+ },
51
+ /** 바뀌었음: delayMs 뒤 저장 (그 사이 또 오면 다시 기다림) */
52
+ schedule() {
53
+ clearTimeout(timer);
54
+ if (state !== 'saving') set('pending');
55
+ else again = true;
56
+ timer = setTimeout(
57
+ () => void run(),
58
+ delayMs
59
+ );
60
+ },
61
+ /** 기다리는 저장이 있으면 바로 (창을 닫기 전 · 제출 전). 없으면 아무것도 하지 않음 */
62
+ flush() {
63
+ if (timer || running) return run();
64
+ return Promise.resolve();
65
+ },
66
+ /** 지금 바로 저장 (워크스페이스 저장 메뉴) */
67
+ saveNow: run,
68
+ };
69
+ }
@@ -0,0 +1,2 @@
1
+ // core/default-project.js 타입 (편집기 자동완성 · 테스트용)
2
+ export declare const DEFAULT_PROJECT: Readonly<Record<string, unknown>>;
@@ -0,0 +1,139 @@
1
+ // 엔트리 기본 작품 (엔트리봇 하나, 시작하기 블록). 열 작품이 없을 때 워크스페이스에 줍니다.
2
+ // 워크스페이스는 "작품 없음"을 받지 못합니다: 빈 답이면 "불러오기에 실패하였습니다" 창을 띄운 뒤 기본 작품을 엽니다.
3
+ // 지금 LXP 엔트리(elice-entry)가 같은 경우에 주는 작품과 같습니다. 그림은 엔트리 서버의 파일 이름으로만 들어 있습니다.
4
+
5
+ /** @type {Readonly<Record<string, unknown>>} */
6
+ export const DEFAULT_PROJECT = Object.freeze({
7
+ "objects": [
8
+ {
9
+ "id": "91or",
10
+ "name": "[묶음] 걷는 모습",
11
+ "script": "[[{\"id\":\"1p6b\",\"x\":19,\"y\":63,\"type\":\"when_run_button_click\",\"params\":[null],\"statements\":[],\"movable\":null,\"deletable\":1,\"emphasized\":false,\"readOnly\":null,\"copyable\":true,\"assemble\":true,\"extensions\":[]},{\"id\":\"alxc\",\"x\":0,\"y\":0,\"type\":\"repeat_basic\",\"params\":[{\"id\":\"6i1j\",\"x\":0,\"y\":0,\"type\":\"number\",\"params\":[\"10\"],\"statements\":[],\"movable\":null,\"deletable\":1,\"emphasized\":false,\"readOnly\":null,\"copyable\":true,\"assemble\":true,\"extensions\":[]},null],\"statements\":[[{\"id\":\"mwog\",\"x\":0,\"y\":0,\"type\":\"move_x\",\"params\":[{\"id\":\"aaoo\",\"x\":0,\"y\":0,\"type\":\"number\",\"params\":[\"10\"],\"statements\":[],\"movable\":null,\"deletable\":1,\"emphasized\":false,\"readOnly\":null,\"copyable\":true,\"assemble\":true,\"extensions\":[]},null],\"statements\":[],\"movable\":null,\"deletable\":1,\"emphasized\":false,\"readOnly\":null,\"copyable\":true,\"assemble\":true,\"extensions\":[]}]],\"movable\":null,\"deletable\":1,\"emphasized\":false,\"readOnly\":null,\"copyable\":true,\"assemble\":true,\"extensions\":[]}]]",
12
+ "objectType": "sprite",
13
+ "rotateMethod": "free",
14
+ "scene": "7dwq",
15
+ "sprite": {
16
+ "pictures": [
17
+ {
18
+ "id": "1n4d",
19
+ "dimension": {
20
+ "width": 144,
21
+ "height": 246,
22
+ "scaleX": 0.5128205128205128,
23
+ "scaleY": 0.5128205128205128
24
+ },
25
+ "filename": "lqw0nhkulp9bio133d9295cf999wy0k3",
26
+ "name": "걷는 엔트리봇_2",
27
+ "imageType": "svg"
28
+ },
29
+ {
30
+ "id": "kw63",
31
+ "dimension": {
32
+ "width": 144,
33
+ "height": 246
34
+ },
35
+ "filename": "14kndnyklp9bio143d9295cf999wzhg7",
36
+ "name": "걷는 엔트리봇_1",
37
+ "imageType": "svg"
38
+ }
39
+ ],
40
+ "sounds": []
41
+ },
42
+ "selectedPictureId": "1n4d",
43
+ "lock": false,
44
+ "entity": {
45
+ "x": 0,
46
+ "y": 0,
47
+ "regX": 72,
48
+ "regY": 123,
49
+ "scaleX": 0.5128205128205128,
50
+ "scaleY": 0.5128205128205128,
51
+ "rotation": 0,
52
+ "direction": 90,
53
+ "width": 144,
54
+ "height": 246,
55
+ "font": "undefinedpx ",
56
+ "visible": true
57
+ },
58
+ "selectedPicture": {
59
+ "id": "1n4d",
60
+ "dimension": {
61
+ "width": 144,
62
+ "height": 246,
63
+ "scaleX": 0.5128205128205128,
64
+ "scaleY": 0.5128205128205128
65
+ },
66
+ "filename": "lqw0nhkulp9bio133d9295cf999wy0k3",
67
+ "name": "[묶음] 걷는 모습",
68
+ "imageType": "svg",
69
+ "_id": "7t903mxdlp9bjgvk2zud95cf99b3nozc",
70
+ "origin": {
71
+ "filename": "lqw0nhkulp9bio133d9295cf999wy0k3",
72
+ "width": 144,
73
+ "height": 246
74
+ },
75
+ "trimmed": {
76
+ "filename": "lqw0nhkulp9bio133d9295cf999wy0k3",
77
+ "width": 144,
78
+ "height": 246
79
+ }
80
+ }
81
+ }
82
+ ],
83
+ "scenes": [
84
+ {
85
+ "id": "7dwq",
86
+ "name": "장면 1"
87
+ }
88
+ ],
89
+ "variables": [
90
+ {
91
+ "name": "초시계",
92
+ "id": "brih",
93
+ "visible": false,
94
+ "value": 0,
95
+ "variableType": "timer",
96
+ "isCloud": false,
97
+ "isRealTime": false,
98
+ "cloudDate": false,
99
+ "object": null,
100
+ "x": 134,
101
+ "y": -70
102
+ },
103
+ {
104
+ "name": " 대답 ",
105
+ "id": "1vu8",
106
+ "visible": false,
107
+ "value": "0",
108
+ "variableType": "answer",
109
+ "isCloud": false,
110
+ "isRealTime": false,
111
+ "cloudDate": false,
112
+ "object": null,
113
+ "x": 150,
114
+ "y": -100
115
+ }
116
+ ],
117
+ "messages": [],
118
+ "functions": [],
119
+ "tables": [],
120
+ "speed": 60,
121
+ "interface": {
122
+ "menuWidth": 280,
123
+ "canvasWidth": 480,
124
+ "object": "91or"
125
+ },
126
+ "expansionBlocks": [],
127
+ "aiUtilizeBlocks": [],
128
+ "hardwareLiteBlocks": [],
129
+ "externalModules": [],
130
+ "externalModulesLite": [],
131
+ "isPracticalCourse": false,
132
+ "name": "elice_entry_sample",
133
+ "isopen": true,
134
+ "recentLikeCnt": 0,
135
+ "childCnt": 0,
136
+ "visit": 0,
137
+ "likeCnt": 0,
138
+ "comment": 0
139
+ });
@@ -0,0 +1,13 @@
1
+ // core/dom.js 타입 (편집기 자동완성 · 테스트용)
2
+ /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ export declare const present: (nodes: any[]) => any[];
4
+ export declare function el(
5
+ tag: string,
6
+ props?: Record<string, unknown>,
7
+ ...children: any[]
8
+ ): HTMLElement;
9
+ /** 최상위 요소가 하나면 그 요소(HTMLElement로 다룸), 아니면 DocumentFragment */
10
+ export declare function html(strings: TemplateStringsArray, ...values: unknown[]): any;
11
+ export declare function part(root: Element, name: string): HTMLElement | null;
12
+ export declare function parts(root: Element, name: string): HTMLElement[];
13
+ export declare function lock<T extends Element>(root: T): T;
@@ -0,0 +1,83 @@
1
+ // 작은 DOM 도우미 (퀴즈 · 영상 템플릿 core/dom.js와 같음). ui/templates/*는 html`…`로 마크업을 쓰고, 동작은 data-role로 그 안의 요소를 찾습니다.
2
+
3
+ /** 조건부로 넣은 null · undefined · false 빼기 */
4
+ export const present = (nodes) => nodes.filter((c) => c !== null && c !== undefined && c !== false);
5
+
6
+ export function el(tag, props = {}, ...children) {
7
+ const node = Object.assign(document.createElement(tag), props);
8
+ node.append(...present(children));
9
+ return node;
10
+ }
11
+
12
+ const escape = (s) =>
13
+ s
14
+ .replace(/&/g, '&amp;')
15
+ .replace(/</g, '&lt;')
16
+ .replace(/>/g, '&gt;')
17
+ .replace(/"/g, '&quot;')
18
+ .replace(/'/g, '&#39;');
19
+
20
+ const MARK = 'en-node:';
21
+
22
+ /**
23
+ * HTML 조각 템플릿. 끼워 넣는 값은
24
+ * 글자 · 숫자 → 이스케이프해서 글자로 (교육자 · 학생이 쓴 내용도 안전)
25
+ * 요소(Node) · 배열 → 그 자리에 그대로 (태그 사이에만, 속성 값에는 글자만)
26
+ * null · undefined · false → 아무것도 넣지 않음 (`${cond && '…'}`)
27
+ * 줄바꿈이 든 앞뒤 공백은 지우므로 들여쓰기를 자유롭게 해도 됩니다 (한 줄 안의 공백은 그대로).
28
+ * 최상위 요소가 하나면 그 요소를, 아니면 DocumentFragment를 돌려준다.
29
+ */
30
+ export function html(strings, ...values) {
31
+ const nodes = [];
32
+ const part = (v) => {
33
+ if (v === null || v === undefined || v === false) return '';
34
+ if (Array.isArray(v)) return v.map(part).join('');
35
+ if (typeof Node !== 'undefined' && v instanceof Node) {
36
+ nodes.push(v);
37
+ return `<!--${MARK}${nodes.length - 1}-->`;
38
+ }
39
+ return escape(String(v));
40
+ };
41
+ const markup = strings.reduce((out, s, i) => out + part(values[i - 1]) + s);
42
+ const template = document.createElement('template');
43
+ // 끼워 넣는 값은 모두 위에서 이스케이프하거나 주석 자리표로 바꾼다 (퀴즈 quiz.test.ts 'html 템플릿'에서 확인)
44
+ // ecdk-ignore-next-line sec.html-injection
45
+ template.innerHTML = markup.trim();
46
+ const walker = document.createTreeWalker(
47
+ template.content,
48
+ NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT,
49
+ );
50
+ const swap = [];
51
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) swap.push(n);
52
+ for (const n of swap) {
53
+ if (n.nodeType === Node.COMMENT_NODE && n.data.startsWith(MARK))
54
+ n.replaceWith(nodes[Number(n.data.slice(MARK.length))]);
55
+ else if (n.nodeType === Node.TEXT_NODE) {
56
+ // 들여쓰기: 줄바꿈이 든 앞뒤 공백은 지우고, 그것만 있는 글자 노드는 뺀다 (JSX와 같은 규칙)
57
+ const data = n.data.replace(/^\s*\n\s*/, '').replace(/\s*\n\s*$/, '');
58
+ if (data === '') n.remove();
59
+ else if (data !== n.data) n.data = data;
60
+ }
61
+ }
62
+ const fragment = template.content;
63
+ return fragment.childNodes.length === 1 && fragment.firstChild instanceof Element
64
+ ? fragment.firstChild
65
+ : fragment;
66
+ }
67
+
68
+ /** root 자신이나 그 안에서 data-role="name"인 첫 요소 */
69
+ export function part(root, name) {
70
+ const selector = `[data-role="${name}"]`;
71
+ return root.matches?.(selector) ? root : root.querySelector(selector);
72
+ }
73
+
74
+ /** root 안의 data-role="name"인 모든 요소 */
75
+ export const parts = (root, name) => [...root.querySelectorAll(`[data-role="${name}"]`)];
76
+
77
+ /** 읽기 전용(교육자 · 튜터링)일 때 root와 그 안의 입력 · 버튼을 모두 막는다 */
78
+ export function lock(root) {
79
+ if ('disabled' in root) root.disabled = true;
80
+ for (const c of root.querySelectorAll('input, textarea, select, button, fieldset'))
81
+ c.disabled = true;
82
+ return root;
83
+ }
@@ -0,0 +1,51 @@
1
+ // core/grading.js 타입 (편집기 자동완성 · 테스트용)
2
+ import type { Packed } from './pack.js';
3
+
4
+ export type GradingMode = 'general' | 'ai';
5
+
6
+ export interface RubricRow {
7
+ /** 엔트리 오브젝트 id (정답 작품에 있는 id, '' = 아직 고르지 않음) */
8
+ object: string;
9
+ criteria: string;
10
+ score: number | null;
11
+ }
12
+
13
+ export type EntryGrading =
14
+ | { type: 'entry'; mode: 'general'; answer_project: Packed }
15
+ | {
16
+ type: 'entry';
17
+ mode: 'ai';
18
+ answer_project: Packed;
19
+ rubrics: { object: string; criteria: string; score: number }[];
20
+ };
21
+
22
+ export declare const GRADING_MODES: readonly GradingMode[];
23
+ export declare const RUBRIC_LIMITS: Readonly<{
24
+ max: number;
25
+ total: number;
26
+ scoreMin: number;
27
+ criteriaMax: number;
28
+ }>;
29
+ export declare function packedProject(raw: unknown): Packed | null;
30
+ export declare function readGrading(raw: unknown): {
31
+ mode: GradingMode;
32
+ rubrics: RubricRow[];
33
+ answerProject: Packed | null;
34
+ };
35
+ export declare function buildGrading(
36
+ value: { mode: string; rubrics: RubricRow[] },
37
+ answerProject: Packed | null
38
+ ): EntryGrading | null;
39
+ export declare function rubricTotal(rubrics: RubricRow[]): number;
40
+ export declare function rubricsProblem(
41
+ rubrics: RubricRow[]
42
+ ):
43
+ | null
44
+ | { code: 'empty' | 'incomplete' | 'score' | 'tooLong' | 'tooMany' }
45
+ | { code: 'total'; total: number };
46
+ export declare function projectObjectIds(project: unknown): Set<string>;
47
+ export declare function projectObjects(
48
+ project: unknown
49
+ ): { id: string; name: string; thumbnail: string }[];
50
+ export declare function hasGradable(project: unknown): boolean;
51
+ export declare function hasUnknownObject(rubrics: RubricRow[], project: unknown): boolean;
@@ -0,0 +1,125 @@
1
+ // 채점 설정(settings.grading) 읽기 · 만들기. 편집 화면 '채점 설정' 탭이 씁니다.
2
+ // 고치지 않습니다: 모양은 서버(엔트리 채점 spec v4)가 정했고 키트 · ecdk 검사가 같은 모양을 받습니다.
3
+ //
4
+ // settings.grading (서버가 학생 · 튜터 · 교육자 화면에는 내려주지 않음, 편집 화면만 받음)
5
+ // 일반: { type: 'entry', mode: 'general', answer_project: { enc, data } }
6
+ // AI: { type: 'entry', mode: 'ai', answer_project: { enc, data }, rubrics: [{ object, criteria, score }] }
7
+ // object = 기준이 보는 엔트리 오브젝트 id (정답 작품에 있는 id. 작품 전체 기준은 없음: ''이나 없는 id는 서버 422
8
+ // entry_rubric_object_not_found), criteria 1~1,000자, score 1~100 정수, 1~10개, 합 100. AI는 settings.entry.startProject도 필요
9
+ // 일반 정답 작품에는 블록 묶음(스크립트)이나 전역 리스트가 하나 이상 있어야 함 (없으면 서버 422 entry_answer_project_empty)
10
+ // 화면 값의 object ''는 '아직 고르지 않음'입니다 (저장을 막음).
11
+ // 정답 작품은 settings.entry에 두지 않습니다 (settings.entry는 학생에게도 내려감).
12
+
13
+ /** 채점 방식 (settings.grading.mode) */
14
+ export const GRADING_MODES = Object.freeze(['general', 'ai']);
15
+
16
+ /** AI 채점 기준 한도 (서버와 같음) */
17
+ export const RUBRIC_LIMITS = Object.freeze({ max: 10, total: 100, scoreMin: 1, criteriaMax: 1000 });
18
+
19
+ const isObject = v => Boolean(v) && typeof v === 'object' && !Array.isArray(v);
20
+
21
+ /** 줄인 작품 모양이면 { enc, data }, 아니면 null */
22
+ export function packedProject(raw) {
23
+ return isObject(raw) && typeof raw.enc === 'string' && typeof raw.data === 'string' && raw.data
24
+ ? { enc: raw.enc, data: raw.data }
25
+ : null;
26
+ }
27
+
28
+ /**
29
+ * 저장된 settings.grading(app.grading)을 편집 화면 값으로. entry가 아니거나 없으면 일반 채점 · 정답 없음
30
+ * @param {unknown} raw
31
+ * @returns {{ mode: 'general' | 'ai', rubrics: { object: string, criteria: string, score: number | null }[], answerProject: { enc: string, data: string } | null }}
32
+ */
33
+ export function readGrading(raw) {
34
+ const g = isObject(raw) && raw.type === 'entry' ? raw : {};
35
+ const list = Array.isArray(g.rubrics) ? g.rubrics : [];
36
+ return {
37
+ mode: g.mode === 'ai' ? 'ai' : 'general',
38
+ rubrics: list
39
+ .filter(isObject)
40
+ .slice(0, RUBRIC_LIMITS.max)
41
+ .map(r => ({
42
+ object: typeof r.object === 'string' ? r.object : '',
43
+ criteria: typeof r.criteria === 'string' ? r.criteria : '',
44
+ score: Number.isInteger(r.score) ? r.score : null,
45
+ })),
46
+ answerProject: packedProject(g.answer_project),
47
+ };
48
+ }
49
+
50
+ /**
51
+ * 편집 화면 값 → settings.grading. 정답 작품이 없으면 null (채점 설정을 만들 수 없음)
52
+ * @param {{ mode: string, rubrics: { object: string, criteria: string, score: number | null }[] }} value
53
+ * @param {{ enc: string, data: string } | null} answerProject
54
+ */
55
+ export function buildGrading(value, answerProject) {
56
+ const answer = packedProject(answerProject);
57
+ if (!answer) return null;
58
+ if (value.mode !== 'ai') return { type: 'entry', mode: 'general', answer_project: answer };
59
+ return {
60
+ type: 'entry',
61
+ mode: 'ai',
62
+ answer_project: answer,
63
+ rubrics: value.rubrics.map(r => ({ object: r.object, criteria: r.criteria.trim(), score: r.score })),
64
+ };
65
+ }
66
+
67
+ /** 부분 점수 합 (빈 칸은 0) */
68
+ export const rubricTotal = rubrics => rubrics.reduce((sum, r) => sum + (r.score ?? 0), 0);
69
+
70
+ /**
71
+ * AI 채점 기준 검사. 문제 없으면 null, 있으면 어떤 문제인지
72
+ * @returns {null | { code: 'empty' | 'incomplete' | 'score' | 'tooLong' | 'tooMany' } | { code: 'total', total: number }}
73
+ */
74
+ export function rubricsProblem(rubrics) {
75
+ if (!rubrics.length) return { code: 'empty' };
76
+ if (rubrics.length > RUBRIC_LIMITS.max) return { code: 'tooMany' };
77
+ if (rubrics.some(r => !r.object || !r.criteria.trim() || r.score === null)) return { code: 'incomplete' };
78
+ if (rubrics.some(r => r.criteria.trim().length > RUBRIC_LIMITS.criteriaMax)) return { code: 'tooLong' };
79
+ if (rubrics.some(r => !Number.isInteger(r.score) || r.score < RUBRIC_LIMITS.scoreMin || r.score > RUBRIC_LIMITS.total))
80
+ return { code: 'score' };
81
+ const total = rubricTotal(rubrics);
82
+ return total === RUBRIC_LIMITS.total ? null : { code: 'total', total };
83
+ }
84
+
85
+ /** 작품(풀어 둔 JSON)의 오브젝트 id들 */
86
+ export function projectObjectIds(project) {
87
+ const objects = isObject(project) && Array.isArray(project.objects) ? project.objects : [];
88
+ return new Set(objects.map(o => (isObject(o) && typeof o.id === 'string' ? o.id : null)).filter(Boolean));
89
+ }
90
+
91
+ /** 작품의 오브젝트 [{ id, name }] (워크스페이스를 띄우기 전, 저장된 작품에서 목록을 만들 때) */
92
+ export function projectObjects(project) {
93
+ const objects = isObject(project) && Array.isArray(project.objects) ? project.objects : [];
94
+ return objects
95
+ .filter(o => isObject(o) && typeof o.id === 'string' && o.id)
96
+ .map(o => ({ id: o.id, name: typeof o.name === 'string' && o.name ? o.name : o.id, thumbnail: '' }));
97
+ }
98
+
99
+ /**
100
+ * 일반 채점의 채점거리가 있나 (서버 entry_answer_project_empty와 같은 규칙): 블록 묶음이 하나 이상 있는 오브젝트나
101
+ * 전역 리스트(variableType 'list', object 없음)가 하나 이상
102
+ */
103
+ export function hasGradable(project) {
104
+ if (!isObject(project) || !Array.isArray(project.objects)) return false;
105
+ const hasScript = project.objects.some(o => {
106
+ let script = isObject(o) ? o.script : undefined;
107
+ if (typeof script === 'string') {
108
+ try {
109
+ script = JSON.parse(script);
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+ return Array.isArray(script) && script.some(thread => Array.isArray(thread) && thread.length > 0);
115
+ });
116
+ if (hasScript) return true;
117
+ const variables = Array.isArray(project.variables) ? project.variables : [];
118
+ return variables.some(v => isObject(v) && v.variableType === 'list' && !v.object);
119
+ }
120
+
121
+ /** 정답 작품에 없는 오브젝트를 고른 기준이 있나 (고르지 않은 '' 줄은 incomplete가 따로 막음) */
122
+ export function hasUnknownObject(rubrics, project) {
123
+ const ids = projectObjectIds(project);
124
+ return rubrics.some(r => r.object && !ids.has(r.object));
125
+ }
@@ -0,0 +1,12 @@
1
+ // core/pack.js 타입 (편집기 자동완성 · 테스트용)
2
+ export interface Packed {
3
+ enc: 'gzip+base64' | 'json';
4
+ data: string;
5
+ }
6
+
7
+ export declare const ENC_GZIP: 'gzip+base64';
8
+ export declare const ENC_JSON: 'json';
9
+ export declare function jsonBytes(value: unknown): number;
10
+ export declare function formatBytes(n: number): string;
11
+ export declare function pack(value: unknown): Promise<Packed>;
12
+ export declare function unpack<T = unknown>(packed: unknown): Promise<T | null>;
@@ -0,0 +1,71 @@
1
+ // 작품 JSON 줄이기 · 풀기. 시작 작품(settings) · 자동 저장(kvstore) · 제출 답에 같은 모양으로 넣습니다.
2
+ // 고치지 않습니다: 모양을 바꾸면 이미 저장한 작품을 읽지 못합니다.
3
+ //
4
+ // 줄인 모양: { enc: 'gzip+base64', data: '…' } (브라우저 CompressionStream으로 gzip, 글자로 base64)
5
+ // CompressionStream이 없는 브라우저: { enc: 'json', data: '…' } (줄이지 않은 JSON 글자)
6
+
7
+ export const ENC_GZIP = 'gzip+base64';
8
+ export const ENC_JSON = 'json';
9
+
10
+ /** 값의 JSON 크기 (UTF-8 바이트). 서버 한도(settings · 제출 답 · kvstore)는 JSON 바이트로 잰다 */
11
+ export function jsonBytes(value) {
12
+ return new TextEncoder().encode(JSON.stringify(value ?? null)).byteLength;
13
+ }
14
+
15
+ /** 바이트 수를 "3.1KB"처럼 */
16
+ export function formatBytes(n) {
17
+ if (n < 1024) return `${n}B`;
18
+ const kb = n / 1024;
19
+ return `${kb < 10 ? kb.toFixed(1) : Math.round(kb)}KB`;
20
+ }
21
+
22
+ const canGzip = () =>
23
+ typeof CompressionStream === 'function' && typeof DecompressionStream === 'function';
24
+
25
+ function toBase64(bytes) {
26
+ let s = '';
27
+ // 큰 배열을 한 번에 넘기면 인자 수 한도에 걸리므로 나눠서
28
+ for (let i = 0; i < bytes.length; i += 0x8000)
29
+ s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
30
+ return btoa(s);
31
+ }
32
+
33
+ function fromBase64(text) {
34
+ const s = atob(text);
35
+ const out = new Uint8Array(s.length);
36
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
37
+ return out;
38
+ }
39
+
40
+ async function pipe(bytes, stream) {
41
+ const res = new Response(new Response(bytes).body.pipeThrough(stream));
42
+ return new Uint8Array(await res.arrayBuffer());
43
+ }
44
+
45
+ /**
46
+ * 작품(JSON 값)을 저장 모양으로 줄인다
47
+ * @param {unknown} value
48
+ * @returns {Promise<{ enc: string, data: string }>}
49
+ */
50
+ export async function pack(value) {
51
+ const json = JSON.stringify(value);
52
+ if (!canGzip()) return { enc: ENC_JSON, data: json };
53
+ const gz = await pipe(new TextEncoder().encode(json), new CompressionStream('gzip'));
54
+ return { enc: ENC_GZIP, data: toBase64(gz) };
55
+ }
56
+
57
+ /**
58
+ * 저장 모양을 작품으로. 모양이 틀리거나 풀지 못하면 null
59
+ * @param {unknown} packed
60
+ */
61
+ export async function unpack(packed) {
62
+ if (!packed || typeof packed !== 'object' || typeof packed.data !== 'string') return null;
63
+ try {
64
+ if (packed.enc === ENC_JSON) return JSON.parse(packed.data);
65
+ if (packed.enc !== ENC_GZIP || !canGzip()) return null;
66
+ const raw = await pipe(fromBase64(packed.data), new DecompressionStream('gzip'));
67
+ return JSON.parse(new TextDecoder().decode(raw));
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
@@ -0,0 +1,33 @@
1
+ // core/settings.js 타입 (편집기 자동완성 · 테스트용)
2
+ import type { Packed } from './pack.js';
3
+
4
+ export type WorkspaceMode = 'block' | 'python';
5
+
6
+ export interface Progress {
7
+ v: number;
8
+ savedAt: string;
9
+ project: Packed;
10
+ }
11
+
12
+ export declare const FORMAT_VERSION: number;
13
+ export declare const PROGRESS_KEY: string;
14
+ export declare const LIMITS: Readonly<{
15
+ settingsBytes: number;
16
+ answerBytes: number;
17
+ kvBytes: number;
18
+ }>;
19
+ export declare const WORKSPACE_MODES: readonly WorkspaceMode[];
20
+ export declare function splitSettings(raw: Record<string, unknown> | null | undefined): {
21
+ rest: Record<string, unknown>;
22
+ entry: Record<string, unknown>;
23
+ };
24
+ export declare function joinSettings(
25
+ rest: Record<string, unknown>,
26
+ entry: Record<string, unknown>
27
+ ): Record<string, unknown>;
28
+ export declare function normalizePreference(raw: unknown): { workspaceMode: WorkspaceMode };
29
+ export declare function progressValue(project: Packed, now?: Date): Progress;
30
+ export declare function answerValue(project: Packed): { v: number; project: Packed };
31
+ export declare function readProgress(
32
+ raw: unknown
33
+ ): { v: unknown; savedAt: string | null; project: Packed } | null;