@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,209 @@
1
+ import { zipSync } from 'fflate';
2
+ import { parseManifest } from './manifest.js';
3
+ import { isUnsafePath, extname, globToRegExp, resolveRef } from './path.js';
4
+ import { lineAt, parseTags, extractRefs, classifyRef } from './refs.js';
5
+ import { lineSkipper } from './skip.js';
6
+ import { rules } from './spec.js';
7
+
8
+ const MB = 1024 * 1024;
9
+ const fmtMB = n => `${(n / MB).toFixed(1)}MB`;
10
+ function matchExclude(path, group) {
11
+ const segs = path.split('/');
12
+ const name = segs[segs.length - 1] ?? '';
13
+ if (group.files.some(g => globToRegExp(g).test(name))) return true;
14
+ return segs.slice(0, -1).some(seg => group.dirs.some(d => d.toLowerCase() === seg.toLowerCase()));
15
+ }
16
+ /** 비밀 값을 찾아볼 텍스트 파일 (이미지 · 글꼴 등 바이너리 제외) */
17
+ const SECRET_SCAN_EXTENSIONS = new Set(['html', 'htm', 'css', 'js', 'mjs', 'json', 'map', 'txt', 'md', 'csv', 'xml', 'vtt', 'svg']);
18
+ /** `<base href>`가 페이지 자기 폴더가 아니면 이유 (문제없으면 null) */
19
+ function baseHrefError(page, href) {
20
+ const kind = classifyRef(href);
21
+ if (kind === 'root' || kind === 'external') return '는 이 페이지의 상대경로를 모두 배포 주소 밖으로 보냅니다. 지워 주세요.';
22
+ if (kind !== 'local') return null;
23
+ // 기준은 폴더: 끝이 /가 아니면 마지막 조각은 파일 이름이라 뺀다
24
+ const clean = href.replace(/[?#].*$/, '');
25
+ const dir = clean.endsWith('/') ? clean : clean.slice(0, clean.lastIndexOf('/') + 1);
26
+ const resolved = resolveRef(page, dir || './');
27
+ if (resolved === null) return '는 zip 밖(배포 주소 밖)을 가리켜 이 페이지의 상대경로가 모두 깨집니다. 지워 주세요.';
28
+ const pageDir = page.split('/').slice(0, -1).join('/');
29
+ if (resolved !== pageDir) return `는 상대경로 기준을 ${resolved || 'zip 최상위'}로 바꿉니다. 검사는 파일 위치 기준이라 ./만 허용합니다. 지우고 경로를 파일 위치 기준으로 써 주세요.`;
30
+ return null;
31
+ }
32
+ function textKind(path) {
33
+ const ext = extname(path);
34
+ if (ext === 'html' || ext === 'htm') return 'html';
35
+ if (ext === 'css') return 'css';
36
+ if (ext === 'js' || ext === 'mjs') return 'js';
37
+ return null;
38
+ }
39
+ /** 최상위에 파일이 없고 폴더가 하나뿐인 zip (폴더째 묶음). 벗겨 내지 않고 거절한다 (ADR 0004). */
40
+ function singleRootFolder(files) {
41
+ const tops = new Set(files.map(f => f.path.split('/')[0]));
42
+ const [only] = tops;
43
+ if (tops.size !== 1 || only === undefined || files.some(f => !f.path.includes('/'))) return null;
44
+ return only;
45
+ }
46
+ function estimateZipBytes(files) {
47
+ return zipSync(Object.fromEntries(files.map(f => [f.path, f.data])), {
48
+ level: 9
49
+ }).byteLength;
50
+ }
51
+ function checkFiles(input, opts = {}) {
52
+ const spec = opts.spec ?? rules;
53
+ const kind = opts.input ?? 'zip';
54
+ const levelOf = new Map(spec.rules.map(r => [r.id, r.level]));
55
+ const issues = [];
56
+ const add = (id, message, path, line) => issues.push({
57
+ id,
58
+ level: levelOf.get(id) ?? 'error',
59
+ message,
60
+ path,
61
+ line
62
+ });
63
+ for (const f of input) {
64
+ if (isUnsafePath(f.path)) add('path.unsafe', `안전하지 않은 경로입니다: ${f.path}`, f.path);
65
+ }
66
+ const files = input.filter(f => !f.dir && !isUnsafePath(f.path));
67
+ if (kind === 'html') add('input.not-zip', 'HTML 파일 하나는 올릴 수 없습니다. metadata.json과 함께 zip으로 묶어 주세요 (ecdk build가 만들어 줍니다).');
68
+ const nestedRoot = singleRootFolder(files);
69
+ if (nestedRoot) add('entry.nested', `모든 파일이 ${nestedRoot}/ 폴더 안에 있습니다. 폴더가 아니라 폴더 안의 파일들을 묶어 주세요 (metadata.json이 zip 최상위에 있어야 합니다).`, `${nestedRoot}/`);
70
+ const exact = new Set(files.map(f => f.path));
71
+ const decoder = new TextDecoder();
72
+ // metadata.json (최상위, 필수)
73
+ let manifest = null;
74
+ const mfile = files.find(f => f.path === spec.manifest.file);
75
+ if (mfile) {
76
+ const parsed = parseManifest(decoder.decode(mfile.data), spec);
77
+ if (parsed.ok) manifest = parsed.manifest;else add('manifest.invalid', `${spec.manifest.file}: ${parsed.error}`, spec.manifest.file);
78
+ } else if (kind !== 'html' && !nestedRoot) {
79
+ add('manifest.missing', `최상위에 ${spec.manifest.file}이 없습니다. 학생 화면·교육자 화면 등 어떤 화면이 있는지 적어 주세요 (ecdk build가 만들어 줍니다).`);
80
+ }
81
+ if (manifest) {
82
+ for (const [mode, file] of Object.entries(manifest.entries)) {
83
+ if (!exact.has(file)) add('manifest.entry-missing', `${spec.manifest.file}에 적은 ${mode} 화면 파일이 없습니다: ${file}`, spec.manifest.file);
84
+ }
85
+ const commentaryFile = manifest.commentary === undefined ? undefined : files.find(f => f.path === manifest.commentary);
86
+ if (manifest.commentary !== undefined && !commentaryFile) add('manifest.entry-missing', `${spec.manifest.file}에 적은 학습 참고 내용 파일이 없습니다: ${manifest.commentary}`, spec.manifest.file);
87
+ // LXP 학습 참고 내용 칸으로 옮길 텍스트라 UTF-8이어야 한다 (메모장 ANSI · EUC-KR 저장이면 깨짐)
88
+ if (commentaryFile) {
89
+ try {
90
+ new TextDecoder('utf-8', {
91
+ fatal: true
92
+ }).decode(commentaryFile.data);
93
+ } catch {
94
+ add('manifest.invalid', `학습 참고 내용 파일이 UTF-8이 아닙니다: ${commentaryFile.path}. UTF-8로 다시 저장해 주세요.`, commentaryFile.path);
95
+ }
96
+ }
97
+ }
98
+ const entry = manifest?.entries.learn ?? spec.manifest.defaultEntry;
99
+ if (!manifest && !exact.has(entry)) add('entry.missing', `최상위에 ${entry} 파일이 없습니다.`);
100
+ // 한도
101
+ const {
102
+ maxFiles,
103
+ maxZipBytes,
104
+ warnRatio,
105
+ maxImageBytes
106
+ } = spec.limits;
107
+ const totalBytes = files.reduce((n, f) => n + f.data.byteLength, 0);
108
+ const zipBytes = opts.zipBytes ?? estimateZipBytes(files);
109
+ if (files.length > maxFiles) add('limit.file-count', `파일이 ${files.length}개입니다 (한도 ${maxFiles}개).`);else if (files.length >= maxFiles * warnRatio) add('limit.near', `파일 ${files.length}개 · 한도 ${maxFiles}개에 가깝습니다.`);
110
+ if (zipBytes > maxZipBytes) add('limit.zip-size', `zip 크기가 ${fmtMB(zipBytes)}입니다 (한도 ${fmtMB(maxZipBytes)}). 영상은 비디오 자료로 따로 올리고 이미지는 줄여 주세요.`);else if (zipBytes >= maxZipBytes * warnRatio) add('limit.near', `zip ${fmtMB(zipBytes)} · 한도 ${fmtMB(maxZipBytes)}에 가깝습니다.`);
111
+ // 경로 · 파일 종류
112
+ const byLower = new Map();
113
+ for (const f of files) {
114
+ const key = f.path.toLowerCase();
115
+ byLower.set(key, [...(byLower.get(key) ?? []), f.path]);
116
+ if (/[^\x21-\x7e]/.test(f.path)) add('path.non-ascii', `공백이나 ASCII 밖 문자가 든 경로입니다: ${f.path}`, f.path);
117
+ if (matchExclude(f.path, spec.excluded.secret)) add('file.secret', `정답·비밀 파일은 올리면 안 됩니다: ${f.path}`, f.path);else if (matchExclude(f.path, spec.excluded.dev)) add('file.dev', `개발용 폴더의 파일입니다: ${f.path}`, f.path);else if (matchExclude(f.path, spec.excluded.junk)) add('file.junk', `불필요한 파일입니다: ${f.path}`, f.path);else if (!spec.allowedExtensions.includes(extname(f.path))) add('file.extension', `허용하지 않는 파일 종류입니다: ${f.path}`, f.path);else if (spec.imageExtensions.includes(extname(f.path)) && f.data.byteLength > maxImageBytes) add('file.large-image', `${fmtMB(maxImageBytes)}가 넘는 이미지입니다 (${fmtMB(f.data.byteLength)}). 줄이면 학생 화면이 빨리 열립니다: ${f.path}`, f.path);
118
+ }
119
+ for (const paths of byLower.values()) {
120
+ if (paths.length > 1) add('path.case-collision', `대소문자만 다른 경로가 있습니다: ${paths.join(', ')}`, paths[0]);
121
+ }
122
+ // 참조 · 태그 · API (텍스트 파일)
123
+ const apis = spec.forbiddenApis.map(a => ({
124
+ ...a,
125
+ re: new RegExp(a.pattern, 'g')
126
+ }));
127
+ const checkRef = (from, ref) => {
128
+ const type = classifyRef(ref.value);
129
+ if (type === 'skip') return;
130
+ if (type === 'external') {
131
+ if (ref.role === 'script') add('ref.external-script', `외부 스크립트를 불러옵니다: ${ref.value}. 스크립트 파일을 zip 안에 넣고 상대경로로 불러와 주세요.`, from, ref.line);else if (ref.role === 'resource' && /^http:/i.test(ref.value)) add('ref.insecure', `http:// 리소스는 https 페이지에서 막힙니다: ${ref.value}`, from, ref.line);else if (ref.role === 'resource') add('ref.external-request', `zip 밖 리소스를 불러옵니다: ${ref.value}. 막히면 글꼴·이미지가 보이지 않으니 zip 안에 넣어 주세요.`, from, ref.line);
132
+ return;
133
+ }
134
+ if (type === 'root') add('ref.root-absolute', `/로 시작하는 경로는 배포 주소에서 깨집니다. 상대경로로 바꿔 주세요: ${ref.value}`, from, ref.line);
135
+ let clean = ref.value.replace(/[?#].*$/, '');
136
+ try {
137
+ clean = decodeURI(clean);
138
+ } catch {
139
+ // 잘못된 % 인코딩은 그대로 비교
140
+ }
141
+ const target = resolveRef(from, clean);
142
+ const candidates = target === null ? [] : clean.endsWith('/') || target === '' ? [`${target}${target ? '/' : ''}index.html`] : [target];
143
+ if (candidates.some(c => exact.has(c))) return;
144
+ const ci = candidates.flatMap(c => byLower.get(c.toLowerCase()) ?? []);
145
+ if (ci.length > 0) add('ref.case-mismatch', `${ref.value}를 참조했지만 실제 파일은 ${ci[0]}입니다 (서버는 대소문자를 구분합니다).`, from, ref.line);else if (type !== 'root') add('ref.missing', `참조한 파일이 없습니다: ${ref.value}`, from, ref.line);
146
+ };
147
+ // 비밀 값: 주석 안에 있어도 유출이라 주석 줄도 본다. 값은 메시지에 싣지 않는다
148
+ const secrets = spec.secretPatterns.map(s => ({
149
+ ...s,
150
+ re: new RegExp(s.pattern, `${s.flags ?? ''}g`),
151
+ notRe: s.not ? new RegExp(s.not, 'i') : null
152
+ }));
153
+ for (const f of files) {
154
+ if (!SECRET_SCAN_EXTENSIONS.has(extname(f.path)) || matchExclude(f.path, spec.excluded.dev)) continue;
155
+ const text = decoder.decode(f.data);
156
+ const skip = lineSkipper(text, {
157
+ skipComments: false
158
+ });
159
+ for (const s of secrets) {
160
+ for (const m of text.matchAll(s.re)) {
161
+ if (s.notRe?.test(m[0])) continue;
162
+ const line = lineAt(text, m.index);
163
+ if (skip.isSkipped(line, 'sec.secret')) continue;
164
+ add('sec.secret', `${s.title}로 보이는 값이 있습니다 (semgrep ${s.source}). 이미 올렸다면 키를 폐기하고, zip에서 빼 주세요.`, f.path, line);
165
+ break;
166
+ }
167
+ }
168
+ }
169
+ for (const f of files) {
170
+ const kindOf = textKind(f.path);
171
+ if (!kindOf || matchExclude(f.path, spec.excluded.dev)) continue;
172
+ const text = decoder.decode(f.data);
173
+ const tags = kindOf === 'html' ? parseTags(text) : [];
174
+ for (const ref of extractRefs(kindOf, text, tags)) checkRef(f.path, ref);
175
+ for (const t of tags) {
176
+ // <base href>는 그 페이지 모든 상대경로의 기준을 바꾼다. 페이지 자기 폴더(./)만 허용한다:
177
+ // /·외부 주소·zip 밖(../)은 배포 주소(/s/{서명}/) 밖으로 나가고, 하위 폴더는 참조 검사(파일 위치 기준)와 어긋난다
178
+ const baseHref = t.name === 'base' ? t.attrs.get('href')?.trim() : undefined;
179
+ const baseError = baseHref === undefined ? null : baseHrefError(f.path, baseHref);
180
+ if (baseHref !== undefined && baseError) add('ref.root-absolute', `<base href="${baseHref}">${baseError}`, f.path, t.line);
181
+ if (t.name === 'img' && !t.attrs.has('alt')) add('html.img-alt', `대체 텍스트(alt)가 없는 이미지입니다.`, f.path, t.line);
182
+ if (t.name === 'form') add('html.form', 'form 제출은 sandbox에서 막힙니다. 버튼 click 처리와 SDK 제출을 써 주세요.', f.path, t.line);
183
+ }
184
+ if (kindOf === 'css') continue;
185
+ const skip = lineSkipper(text);
186
+ for (const api of apis) {
187
+ // 파일마다 처음 걸린 곳 하나만. 주석뿐인 줄과 ecdk-ignore 주석으로 끈 줄은 건너뛴다 (skip.ts)
188
+ for (const m of text.matchAll(api.re)) {
189
+ const line = lineAt(text, m.index);
190
+ if (skip.isSkipped(line, api.id)) continue;
191
+ add(api.id, `${api.title}: ${m[0]}`, f.path, line);
192
+ break;
193
+ }
194
+ }
195
+ }
196
+ return {
197
+ ok: !issues.some(i => i.level === 'error'),
198
+ rulesVersion: spec.version,
199
+ stats: {
200
+ files: files.length,
201
+ totalBytes,
202
+ zipBytes
203
+ },
204
+ manifest,
205
+ issues
206
+ };
207
+ }
208
+
209
+ export { checkFiles };
@@ -0,0 +1,8 @@
1
+ export { checkFiles } from './check.js';
2
+ export { gradingTypesError, parseManifest, serializeManifest } from './manifest.js';
3
+ export { globToRegExp } from './path.js';
4
+ export { commentOnlyLines, lineSkipper } from './skip.js';
5
+ export { rules, RULES_VERSION } from './spec.js';
6
+ export { findUnreferenced } from './unused.js';
7
+ export { filesFromHtml, filesFromZip, ZipLimitError } from './zip.js';
8
+ export type * from './types.js';
@@ -0,0 +1,7 @@
1
+ export { checkFiles } from './check.js';
2
+ export { gradingTypesError, parseManifest, serializeManifest } from './manifest.js';
3
+ export { globToRegExp } from './path.js';
4
+ export { commentOnlyLines, lineSkipper } from './skip.js';
5
+ export { RULES_VERSION, rules } from './spec.js';
6
+ export { findUnreferenced } from './unused.js';
7
+ export { ZipLimitError, filesFromHtml, filesFromZip } from './zip.js';
@@ -0,0 +1,39 @@
1
+ import type { Manifest, RulesSpec } from './types.js';
2
+ export type ParsedManifest = {
3
+ ok: true;
4
+ manifest: Manifest;
5
+ } | {
6
+ ok: false;
7
+ error: string;
8
+ };
9
+ /**
10
+ * 지원 채점 유형 목록 검사 (metadata.json · elice.config.json 공통). 문제가 없으면 null.
11
+ * 수동 채점(manual) · 채점 없음(none)은 Custom HTML에서 쓰지 않는다.
12
+ */
13
+ export declare function gradingTypesError(value: unknown, allowed: readonly string[]): string | null;
14
+ /**
15
+ * metadata.json (zip 최상위): 용도, 화면(모드)별 사용 여부와 진입 파일, 빌드 정보. 정답은 넣지 않는다.
16
+ *
17
+ * {
18
+ * "kind": "material", // 선택. material: 자료 본문(기본) · description: 문제 설명
19
+ * "screens": { // 화면 3개 모두 적는다
20
+ * "learn": { "enabled": true, "entry": "index.html" },
21
+ * "instructor": { "enabled": true, "entry": "instructor.html" },
22
+ * "edit": { "enabled": false }
23
+ * },
24
+ * // 이 자료가 지원하는 채점 유형 모두 (교육자가 LXP 채점 설정에서 하나를 고름). 자료 본문은 필수, 문제 설명에는 없음
25
+ * // on_access · on_submit · pattern · rubric (rules.json manifest.gradingTypes). manual · none은 없음
26
+ * "gradingTypes": ["on_access", "on_submit", "pattern", "rubric"],
27
+ * "commentary": "commentary.txt", // 선택. 학습 참고 내용 파일 (zip 최상위, 일반 텍스트)
28
+ * "build": { "cli": "0.1.0", "rules": "0.2.0", "protocol": 1, "engine": "static" } // 선택
29
+ * }
30
+ *
31
+ * 파싱 결과의 `entries`는 켠 화면만 담는다. 서버 `material_draft.manifest`(JSONB) · SDK `MaterialManifest`의
32
+ * `{ entries }`가 이 모양이라 서버는 그대로 저장할 수 있다. 형식은 서버·디자인과 확정 전 제안안 (ADR 0004).
33
+ */
34
+ export declare function parseManifest(text: string, spec: RulesSpec): ParsedManifest;
35
+ /**
36
+ * 화면 3개의 사용 여부(enabled)를 모두 적는다. 필드 순서(kind · screens · gradingTypes · commentary · build)와 화면 순서(learn · instructor · edit)를
37
+ * 고정해 같은 입력이면 같은 파일이 나오게 한다. kind가 없으면 기본값을 적는다.
38
+ */
39
+ export declare function serializeManifest(manifest: Manifest, spec: RulesSpec): string;
@@ -0,0 +1,168 @@
1
+ const isRecord = v => typeof v === 'object' && v !== null && !Array.isArray(v);
2
+ /**
3
+ * metadata.json에 적는 파일 이름(진입 파일 · 학습 참고 내용): zip 최상위, 영문 · 숫자 · `.` · `_` · `-`만.
4
+ * LXP가 배포 주소 뒤에 그대로 붙여 열므로 공백 · 한글 · `?` · `#` · `%`처럼 URL 인코딩이 필요한 글자는 받지 않는다.
5
+ */
6
+ const SAFE_FILE_NAME = /^[A-Za-z0-9._-]+$/;
7
+ const HTML_FILE = /\.html?$/i;
8
+ function fileNameError(name, label) {
9
+ if (name.includes('/') || name.includes('\\')) return `${label}은 zip 최상위에 있어야 합니다: ${name}`;
10
+ if (!SAFE_FILE_NAME.test(name) || name.startsWith('.')) return `${label} 이름은 영문 · 숫자 · . · _ · -만 씁니다 (LXP가 주소에 그대로 붙임): ${name}`;
11
+ return null;
12
+ }
13
+ /**
14
+ * 지원 채점 유형 목록 검사 (metadata.json · elice.config.json 공통). 문제가 없으면 null.
15
+ * 수동 채점(manual) · 채점 없음(none)은 Custom HTML에서 쓰지 않는다.
16
+ */
17
+ function gradingTypesError(value, allowed) {
18
+ if (!Array.isArray(value) || value.length === 0 || !value.every(t => typeof t === 'string')) return `gradingTypes는 지원하는 채점 유형을 하나 이상 적은 배열입니다. 예: ["on_submit", "pattern"] (가능: ${allowed.join(', ')})`;
19
+ const types = value;
20
+ if (types.includes('manual')) return `수동 채점(manual)은 Custom HTML 자료에서 쓰지 않습니다. ${allowed.join(' · ')} 중에서 고르세요.`;
21
+ if (types.includes('none')) return '채점 없음(none)은 Custom HTML 자료에서 쓰지 않습니다. 보기만 하는 자료는 on_access, 제출만 받는 자료는 on_submit.';
22
+ const unknown = types.find(t => !allowed.includes(t));
23
+ if (unknown) return `알 수 없는 채점 유형입니다: ${unknown} (가능: ${allowed.join(', ')})`;
24
+ const dup = types.find((t, i) => types.indexOf(t) !== i);
25
+ if (dup) return `gradingTypes에 같은 유형이 두 번 있습니다: ${dup}`;
26
+ return null;
27
+ }
28
+ /**
29
+ * metadata.json (zip 최상위): 용도, 화면(모드)별 사용 여부와 진입 파일, 빌드 정보. 정답은 넣지 않는다.
30
+ *
31
+ * {
32
+ * "kind": "material", // 선택. material: 자료 본문(기본) · description: 문제 설명
33
+ * "screens": { // 화면 3개 모두 적는다
34
+ * "learn": { "enabled": true, "entry": "index.html" },
35
+ * "instructor": { "enabled": true, "entry": "instructor.html" },
36
+ * "edit": { "enabled": false }
37
+ * },
38
+ * // 이 자료가 지원하는 채점 유형 모두 (교육자가 LXP 채점 설정에서 하나를 고름). 자료 본문은 필수, 문제 설명에는 없음
39
+ * // on_access · on_submit · pattern · rubric (rules.json manifest.gradingTypes). manual · none은 없음
40
+ * "gradingTypes": ["on_access", "on_submit", "pattern", "rubric"],
41
+ * "commentary": "commentary.txt", // 선택. 학습 참고 내용 파일 (zip 최상위, 일반 텍스트)
42
+ * "build": { "cli": "0.1.0", "rules": "0.2.0", "protocol": 1, "engine": "static" } // 선택
43
+ * }
44
+ *
45
+ * 파싱 결과의 `entries`는 켠 화면만 담는다. 서버 `material_draft.manifest`(JSONB) · SDK `MaterialManifest`의
46
+ * `{ entries }`가 이 모양이라 서버는 그대로 저장할 수 있다. 형식은 서버·디자인과 확정 전 제안안 (ADR 0004).
47
+ */
48
+ function parseManifest(text, spec) {
49
+ const fail = error => ({
50
+ ok: false,
51
+ error
52
+ });
53
+ let json;
54
+ try {
55
+ json = JSON.parse(text);
56
+ } catch (e) {
57
+ return fail(`JSON 형식이 아닙니다 (${e.message}).`);
58
+ }
59
+ if (isRecord(json) && json.entries !== undefined && json.screens === undefined) return fail('"entries" 대신 "screens"에 화면마다 사용 여부(enabled)를 적어 주세요. 예: { "screens": { "learn": { "enabled": true, "entry": "index.html" }, "instructor": { "enabled": false }, "edit": { "enabled": false } } }');
60
+ if (!isRecord(json) || !isRecord(json.screens)) return fail('"screens" 객체가 없습니다. 예: { "screens": { "learn": { "enabled": true, "entry": "index.html" }, "instructor": { "enabled": false }, "edit": { "enabled": false } } }');
61
+ if (json.kind !== undefined && !spec.manifest.kinds.includes(json.kind)) return fail(`"kind"는 ${spec.manifest.kinds.join(' · ')} 중 하나여야 합니다 (material: 자료 본문, description: 문제 설명). 없으면 ${spec.manifest.defaultKind}.`);
62
+ const kind = json.kind;
63
+ const unknown = Object.keys(json.screens).find(m => !spec.manifest.modes.includes(m));
64
+ if (unknown) return fail(`알 수 없는 화면입니다: ${unknown} (가능: ${spec.manifest.modes.join(', ')})`);
65
+ const entries = {};
66
+ for (const mode of spec.manifest.modes) {
67
+ const s = json.screens[mode];
68
+ if (s === undefined) return fail(`${mode} 화면의 사용 여부가 없습니다. 쓰지 않으면 { "enabled": false }`);
69
+ if (!isRecord(s) || typeof s.enabled !== 'boolean') return fail(`${mode} 화면은 { "enabled": true|false, "entry": "파일" } 모양이어야 합니다.`);
70
+ if (!s.enabled) {
71
+ if (s.entry !== undefined) return fail(`${mode} 화면은 꺼져 있는데(enabled: false) entry가 있습니다. 둘 중 하나를 고쳐 주세요.`);
72
+ continue;
73
+ }
74
+ const file = s.entry;
75
+ if (typeof file !== 'string' || file.trim() === '') return fail(`${mode} 화면의 entry(진입 파일)가 비어 있거나 문자열이 아닙니다.`);
76
+ const nameError = fileNameError(file.trim(), `${mode} 화면의 진입 파일`);
77
+ if (nameError) return fail(nameError);
78
+ if (!HTML_FILE.test(file.trim())) return fail(`진입 파일은 HTML(.html)이어야 합니다: ${mode} → ${file}`);
79
+ entries[mode] = file.trim();
80
+ }
81
+ const missing = spec.manifest.required.filter(m => !entries[m]);
82
+ if (missing.length > 0) return fail(`반드시 켜야 하는 화면입니다 (enabled: true): ${missing.join(', ')}`);
83
+ const allowed = spec.manifest.kindModes[kind ?? spec.manifest.defaultKind] ?? spec.manifest.modes;
84
+ const extra = Object.keys(entries).filter(m => !allowed.includes(m));
85
+ if (extra.length > 0) return fail(`${kind === 'description' ? '문제 설명' : kind} 용도는 ${allowed.join(' · ')} 화면만 지원합니다: ${extra.join(', ')}를 { "enabled": false }로 바꿔 주세요.`);
86
+ // 채점 방식: 이 자료가 지원하는 채점 유형 목록 (교육자가 LXP 채점 설정에서 이 중 하나를 고름)
87
+ if (json.grading !== undefined) return fail('"grading" 대신 "gradingTypes"에 이 자료가 지원하는 채점 유형을 모두 적어 주세요. 예: "gradingTypes": ["on_submit", "pattern"]');
88
+ const isDescription = (kind ?? spec.manifest.defaultKind) === 'description';
89
+ let gradingTypes;
90
+ if (json.gradingTypes !== undefined) {
91
+ if (isDescription) return fail('문제 설명(kind: description)은 채점하지 않습니다. gradingTypes를 지워 주세요.');
92
+ const error = gradingTypesError(json.gradingTypes, spec.manifest.gradingTypes);
93
+ if (error) return fail(error);
94
+ gradingTypes = json.gradingTypes;
95
+ } else if (!isDescription) {
96
+ return fail(`자료 본문에는 지원하는 채점 유형이 있어야 합니다: "gradingTypes": [${spec.manifest.gradingTypes.map(t => `"${t}"`).join(', ')}] 중 하나 이상. 보기만 하는 자료는 ["on_access"].`);
97
+ }
98
+ const commentary = json.commentary;
99
+ if (commentary !== undefined) {
100
+ if (typeof commentary !== 'string' || commentary.trim() === '') return fail('"commentary"(학습 참고 내용)는 파일 이름이어야 합니다. 예: "commentary.txt"');
101
+ const nameError = fileNameError(commentary.trim(), '학습 참고 내용 파일');
102
+ if (nameError) return fail(nameError);
103
+ if (!/\.txt$/i.test(commentary)) return fail(`학습 참고 내용은 일반 텍스트(.txt) 파일입니다: ${commentary}. LXP의 학습 참고 내용 칸이 서식 없는 텍스트라서입니다.`);
104
+ }
105
+ let build;
106
+ if (json.build !== undefined) {
107
+ const b = json.build;
108
+ if (!isRecord(b) || typeof b.cli !== 'string' || typeof b.rules !== 'string' || typeof b.protocol !== 'number' || typeof b.engine !== 'string') return fail('"build"는 { cli, rules, protocol, engine } 모양이어야 합니다 (없어도 됩니다).');
109
+ build = {
110
+ cli: b.cli,
111
+ rules: b.rules,
112
+ protocol: b.protocol,
113
+ engine: b.engine
114
+ };
115
+ // 선택 필드는 모양이 맞을 때만 남긴다 (없거나 틀려도 오류는 아님)
116
+ for (const key of ['template', 'sdk', 'digest']) if (typeof b[key] === 'string') build[key] = b[key];
117
+ if (typeof b.minify === 'boolean') build.minify = b.minify;
118
+ }
119
+ return {
120
+ ok: true,
121
+ manifest: {
122
+ ...(kind ? {
123
+ kind
124
+ } : {}),
125
+ entries,
126
+ ...(gradingTypes ? {
127
+ gradingTypes
128
+ } : {}),
129
+ ...(typeof commentary === 'string' ? {
130
+ commentary: commentary.trim()
131
+ } : {}),
132
+ ...(build ? {
133
+ build
134
+ } : {})
135
+ }
136
+ };
137
+ }
138
+ /**
139
+ * 화면 3개의 사용 여부(enabled)를 모두 적는다. 필드 순서(kind · screens · gradingTypes · commentary · build)와 화면 순서(learn · instructor · edit)를
140
+ * 고정해 같은 입력이면 같은 파일이 나오게 한다. kind가 없으면 기본값을 적는다.
141
+ */
142
+ function serializeManifest(manifest, spec) {
143
+ const screens = Object.fromEntries(spec.manifest.modes.map(m => {
144
+ const entry = manifest.entries[m];
145
+ return [m, entry ? {
146
+ enabled: true,
147
+ entry
148
+ } : {
149
+ enabled: false
150
+ }];
151
+ }));
152
+ const out = {
153
+ kind: manifest.kind ?? spec.manifest.defaultKind,
154
+ screens,
155
+ ...(manifest.gradingTypes ? {
156
+ gradingTypes: [...manifest.gradingTypes]
157
+ } : {}),
158
+ ...(manifest.commentary !== undefined ? {
159
+ commentary: manifest.commentary
160
+ } : {}),
161
+ ...(manifest.build ? {
162
+ build: manifest.build
163
+ } : {})
164
+ };
165
+ return `${JSON.stringify(out, null, 2)}\n`;
166
+ }
167
+
168
+ export { gradingTypesError, parseManifest, serializeManifest };
@@ -0,0 +1,11 @@
1
+ import type { CheckResult, ContentFile, InputKind } from './types.js';
2
+ /** 개발용 폴더는 안으로 들어가지 않고 폴더 안 첫 항목 하나로만 표시한다 (node_modules 전체를 읽지 않도록). */
3
+ export declare function filesFromDir(root: string): Promise<ContentFile[]>;
4
+ /** 폴더, .zip, .html 중 무엇이든 받아 ContentFile 목록과 입력 종류로. */
5
+ export declare function filesFromPath(p: string): Promise<{
6
+ files: ContentFile[];
7
+ input: InputKind;
8
+ zipBytes?: number;
9
+ }>;
10
+ export declare function checkPath(p: string): Promise<CheckResult>;
11
+ export * from './index.js';
@@ -0,0 +1,87 @@
1
+ import { stat, readFile, readdir } from 'node:fs/promises';
2
+ import { extname, join, relative, sep } from 'node:path';
3
+ import { checkFiles } from './check.js';
4
+ import { rules } from './spec.js';
5
+ export { RULES_VERSION } from './spec.js';
6
+ import { ZipLimitError, filesFromZip, filesFromHtml } from './zip.js';
7
+
8
+ /** 개발용 폴더는 안으로 들어가지 않고 폴더 안 첫 항목 하나로만 표시한다 (node_modules 전체를 읽지 않도록). */
9
+ async function filesFromDir(root) {
10
+ const out = [];
11
+ const devDirs = new Set(rules.excluded.dev.dirs.map(d => d.toLowerCase()));
12
+ async function walk(dir) {
13
+ const entries = await readdir(dir, {
14
+ withFileTypes: true
15
+ });
16
+ entries.sort((a, b) => a.name.localeCompare(b.name));
17
+ for (const e of entries) {
18
+ const abs = join(dir, e.name);
19
+ const rel = relative(root, abs).split(sep).join('/');
20
+ if (e.isDirectory()) {
21
+ if (devDirs.has(e.name.toLowerCase())) out.push({
22
+ path: `${rel}/...`,
23
+ data: new Uint8Array()
24
+ });else await walk(abs);
25
+ } else if (e.isFile()) {
26
+ out.push({
27
+ path: rel,
28
+ data: new Uint8Array(await readFile(abs))
29
+ });
30
+ }
31
+ }
32
+ }
33
+ await walk(root);
34
+ return out;
35
+ }
36
+ /** 폴더, .zip, .html 중 무엇이든 받아 ContentFile 목록과 입력 종류로. */
37
+ async function filesFromPath(p) {
38
+ if ((await stat(p)).isDirectory()) return {
39
+ files: await filesFromDir(p),
40
+ input: 'dir'
41
+ };
42
+ const data = new Uint8Array(await readFile(p));
43
+ const ext = extname(p).toLowerCase();
44
+ if (ext === '.zip') return {
45
+ files: filesFromZip(data),
46
+ input: 'zip',
47
+ zipBytes: data.byteLength
48
+ };
49
+ if (ext === '.html' || ext === '.htm') return {
50
+ files: filesFromHtml(data),
51
+ input: 'html'
52
+ };
53
+ throw new Error(`폴더, .zip, .html만 검사할 수 있습니다: ${p}`);
54
+ }
55
+ async function checkPath(p) {
56
+ try {
57
+ const {
58
+ files,
59
+ input,
60
+ zipBytes
61
+ } = await filesFromPath(p);
62
+ return checkFiles(files, {
63
+ input,
64
+ zipBytes
65
+ });
66
+ } catch (e) {
67
+ if (!(e instanceof ZipLimitError)) throw e;
68
+ // 풀다가 멈춘 zip: 파일을 읽지 않았으므로 이 오류 하나만
69
+ return {
70
+ ok: false,
71
+ rulesVersion: rules.version,
72
+ stats: {
73
+ files: 0,
74
+ totalBytes: 0,
75
+ zipBytes: (await stat(p)).size
76
+ },
77
+ manifest: null,
78
+ issues: [{
79
+ id: e.id,
80
+ level: 'error',
81
+ message: e.message
82
+ }]
83
+ };
84
+ }
85
+ }
86
+
87
+ export { ZipLimitError, checkFiles, checkPath, filesFromDir, filesFromHtml, filesFromPath, filesFromZip, rules };
@@ -0,0 +1,7 @@
1
+ /** 서버 `check_zipfile()`(elice-api api/func/remote_file/func.py)과 같은 기준: 정규화 결과가 원래 이름과 같아야 한다. */
2
+ export declare function isUnsafePath(name: string): boolean;
3
+ /** `from` 파일 기준으로 상대 참조를 풀어 루트 기준 경로로. 루트 밖으로 나가면 null. */
4
+ export declare function resolveRef(from: string, ref: string): string | null;
5
+ export declare function basename(p: string): string;
6
+ export declare function extname(p: string): string;
7
+ export declare function globToRegExp(glob: string): RegExp;
@@ -0,0 +1,35 @@
1
+ /** 서버 `check_zipfile()`(elice-api api/func/remote_file/func.py)과 같은 기준: 정규화 결과가 원래 이름과 같아야 한다. */
2
+ function isUnsafePath(name) {
3
+ const p = name.endsWith('/') ? name.slice(0, -1) : name;
4
+ if (p === '' || p.startsWith('/') || p.includes('\\') || /^[a-zA-Z]:/.test(p)) return true;
5
+ return p.split('/').some(seg => seg === '' || seg === '.' || seg === '..');
6
+ }
7
+ /** `from` 파일 기준으로 상대 참조를 풀어 루트 기준 경로로. 루트 밖으로 나가면 null. */
8
+ function resolveRef(from, ref) {
9
+ const base = from.split('/').slice(0, -1);
10
+ const out = ref.startsWith('/') ? [] : base;
11
+ for (const seg of ref.split('/')) {
12
+ if (seg === '' || seg === '.') continue;
13
+ if (seg === '..') {
14
+ if (out.length === 0) return null;
15
+ out.pop();
16
+ } else {
17
+ out.push(seg);
18
+ }
19
+ }
20
+ return out.join('/');
21
+ }
22
+ function basename(p) {
23
+ return p.slice(p.lastIndexOf('/') + 1);
24
+ }
25
+ function extname(p) {
26
+ const b = basename(p);
27
+ const i = b.lastIndexOf('.');
28
+ return i <= 0 ? '' : b.slice(i + 1).toLowerCase();
29
+ }
30
+ function globToRegExp(glob) {
31
+ const src = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
32
+ return new RegExp(`^${src}$`, 'i');
33
+ }
34
+
35
+ export { basename, extname, globToRegExp, isUnsafePath, resolveRef };
@@ -0,0 +1,19 @@
1
+ /** script: 실행되는 코드(외부면 오류), resource: 화면이 불러오는 파일(외부면 경고), link: 이동 링크(외부면 무시) */
2
+ export type RefRole = 'script' | 'resource' | 'link';
3
+ export interface Ref {
4
+ value: string;
5
+ line: number;
6
+ role: RefRole;
7
+ }
8
+ export interface HtmlTag {
9
+ name: string;
10
+ attrs: Map<string, string>;
11
+ line: number;
12
+ }
13
+ declare function lineAt(text: string, index: number): number;
14
+ export declare function parseTags(html: string): HtmlTag[];
15
+ /** HTML 태그 속성, CSS url()·@import, JS 정적·동적 import의 문자열 리터럴 참조. 스크립트가 만든 경로(fetch 등)는 못 잡는다. */
16
+ export declare function extractRefs(kind: 'html' | 'css' | 'js', text: string, tags?: HtmlTag[]): Ref[];
17
+ export type RefKind = 'local' | 'root' | 'external' | 'skip';
18
+ export declare function classifyRef(value: string): RefKind;
19
+ export { lineAt };