@eliceio/cdk-cli 0.1.0-alpha.6 → 0.1.0-alpha.8

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 (87) hide show
  1. package/README.md +110 -104
  2. package/es/cli.js +7 -22
  3. package/es/commands/build/index.d.ts +3 -21
  4. package/es/commands/build/index.js +17 -140
  5. package/es/commands/create/scaffold.d.ts +2 -0
  6. package/es/commands/create/scaffold.js +15 -1
  7. package/es/commands/doctor/index.d.ts +4 -3
  8. package/es/commands/doctor/index.js +14 -14
  9. package/es/commands/setup/index.d.ts +4 -7
  10. package/es/commands/setup/index.js +41 -70
  11. package/es/commands/uninstall/index.d.ts +9 -8
  12. package/es/commands/uninstall/index.js +41 -47
  13. package/es/commands/update/index.d.ts +4 -2
  14. package/es/commands/update/index.js +27 -18
  15. package/es/commands/validate/index.js +3 -1
  16. package/es/core/collect.d.ts +1 -1
  17. package/es/core/collect.js +3 -1
  18. package/es/core/config.d.ts +2 -2
  19. package/es/core/config.js +3 -3
  20. package/es/core/manifest.d.ts +3 -3
  21. package/es/core/manifest.js +4 -8
  22. package/es/{commands/mcp/index.d.ts → core/mcp.d.ts} +11 -18
  23. package/es/{commands/mcp/index.js → core/mcp.js} +29 -51
  24. package/es/core/prepare.d.ts +15 -10
  25. package/es/core/prepare.js +35 -35
  26. package/es/core/project-check.d.ts +6 -5
  27. package/es/core/project-check.js +9 -9
  28. package/es/core/sandbox.d.ts +6 -5
  29. package/es/core/sandbox.js +30 -8
  30. package/es/core/sdk.d.ts +7 -18
  31. package/es/core/sdk.js +8 -38
  32. package/es/{commands/skill/index.d.ts → core/skills.d.ts} +1 -17
  33. package/es/{commands/skill/index.js → core/skills.js} +6 -22
  34. package/es/dev/grading.d.ts +1 -1
  35. package/es/dev/grading.js +1 -1
  36. package/es/dev/host-page.js +2 -2
  37. package/es/dev/server.d.ts +6 -4
  38. package/es/dev/server.js +47 -77
  39. package/es/engines/vite/index.d.ts +2 -2
  40. package/es/engines/vite/index.js +2 -4
  41. package/es/engines/vite/plugin.d.ts +58 -0
  42. package/es/engines/vite/plugin.js +286 -0
  43. package/es/engines/vite/run.d.ts +15 -0
  44. package/es/engines/vite/run.js +92 -0
  45. package/es/rules/check.js +10 -12
  46. package/es/rules/csp.d.ts +1 -1
  47. package/es/rules/csp.js +1 -1
  48. package/es/rules/types.d.ts +8 -3
  49. package/es/rules.json.js +1 -1
  50. package/es/test-packages.d.ts +3 -1
  51. package/package.json +8 -3
  52. package/rules.json +9 -3
  53. package/skills/_shared/always.md +1 -1
  54. package/skills/elice-content-create/SKILL.md +2 -1
  55. package/skills/elice-content-guide/topics/01-check-the-environment.md +2 -2
  56. package/skills/elice-content-guide/topics/02-design-the-material.md +2 -0
  57. package/skills/elice-content-guide/topics/03-create-the-project.md +3 -3
  58. package/skills/elice-content-guide/topics/04-rules.md +1 -1
  59. package/skills/elice-content-guide/topics/05-screen-code.md +44 -13
  60. package/skills/elice-content-guide/topics/07-move-existing-html.md +2 -2
  61. package/skills/elice-content-guide/topics/08-fix-check-errors.md +21 -21
  62. package/skills/elice-content-guide/topics/10-build.md +1 -1
  63. package/skills/elice-content-guide/topics/12-upload-with-the-material-mcp.md +2 -2
  64. package/skills/elice-content-publish/SKILL.md +1 -1
  65. package/templates/_shared/lib/cdk-mock.js +2 -2
  66. package/templates/_shared/lib/elice-content-editor.d.ts +80 -0
  67. package/templates/_shared/lib/elice-content-editor.js +1062 -0
  68. package/templates/_shared/lib/elice-content.css +332 -0
  69. package/templates/_shared/lib/elice-content.js +18 -15
  70. package/templates/blank/README.md +29 -5
  71. package/templates/blank/commentary.txt +5 -0
  72. package/templates/blank/screens/edit.js +38 -17
  73. package/templates/blank/screens/instructor.js +20 -8
  74. package/templates/blank/screens/learn.js +151 -13
  75. package/templates/blank/styles.css +171 -0
  76. package/templates/blank/template.json +2 -2
  77. package/templates/quiz/README.md +2 -3
  78. package/templates/quiz/core/model.js +1 -1
  79. package/templates/quiz/screens/edit.js +14 -2
  80. package/templates/quiz/styles.css +11 -0
  81. package/templates/quiz/template.json +1 -1
  82. package/templates/quiz/ui/texts.js +1 -1
  83. package/es/core/minify.d.ts +0 -18
  84. package/es/core/minify.js +0 -93
  85. package/es/engines/static/index.d.ts +0 -3
  86. package/es/engines/static/index.js +0 -11
  87. package/es/engines/types.d.ts +0 -12
@@ -1,4 +1,4 @@
1
- import { compareVersions } from '../../rules/semver.js';
1
+ import { compareVersions } from '../rules/semver.js';
2
2
  export { compareVersions };
3
3
  /** 다른 스킬이 ../elice-content-guide/topics/로 읽는 공유 개발 가이드 스킬 */
4
4
  export declare const GUIDE_SKILL = "elice-content-guide";
@@ -65,19 +65,3 @@ export declare function install(opts: {
65
65
  * Helpy Code 데스크톱은 바로 다시 읽는지 확인하지 못해 다시 시작하라고 한다
66
66
  */
67
67
  export declare function reloadNotes(skillsDirCreated: boolean): string[];
68
- export type PlannedAction = InstallResult['skills'][number]['action'] | 'would-install' | 'would-update';
69
- /** --dry-run: 스킬 폴더를 쓰지 않고 install이 무엇을 할지만 */
70
- export declare function planInstall(opts: {
71
- project: boolean;
72
- force: boolean;
73
- cwd?: string | undefined;
74
- home?: string | undefined;
75
- root?: string | undefined;
76
- version?: string | undefined;
77
- }): {
78
- dir: string;
79
- skills: {
80
- name: string;
81
- action: PlannedAction;
82
- }[];
83
- };
@@ -4,17 +4,17 @@ import { mkdir, copyFile, writeFile } from 'node:fs/promises';
4
4
  import { homedir } from 'node:os';
5
5
  import { join, resolve, dirname, relative, sep } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { compareVersions } from '../../rules/semver.js';
7
+ import { compareVersions } from '../rules/semver.js';
8
8
 
9
9
  /**
10
- * 스킬 설치 · 상태 검사 (명령은 ecdk setup --only skills · ecdk setup · ecdk uninstall · ecdk doctor가 쓴다).
10
+ * 스킬 설치 · 상태 검사 (ecdk setup · update · uninstall · doctor가 쓴다).
11
11
  * 설치 위치는 ~/.claude/skills/ (모든 프로젝트) 또는 --project면 현재 폴더의 .claude/skills/.
12
12
  */
13
- /** CLI 패키지의 skills/ (es/commands/skill/와 src/commands/skill/ 모두 세 단계 위) */
14
- const SKILLS_ROOT = fileURLToPath(new URL('../../../skills', import.meta.url));
13
+ /** CLI 패키지의 skills/ (es/core/와 src/core/ 모두 두 단계 위) */
14
+ const SKILLS_ROOT = fileURLToPath(new URL('../../skills', import.meta.url));
15
15
  /** 모든 스킬에 끼워 넣는 공통 규칙 */
16
16
  const SHARED_DIR = '_shared';
17
- const PACKAGE_VERSION = JSON.parse(readFileSync(fileURLToPath(new URL('../../../package.json', import.meta.url)), 'utf8')).version;
17
+ const PACKAGE_VERSION = JSON.parse(readFileSync(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf8')).version;
18
18
  /** 설치한 스킬 맨 끝 줄. 버전 · 내용 지문으로 오래됨 · 손으로 고침을 알아본다 */
19
19
  const STAMP = /<!-- ecdk-skill: (\S+) (\S+) (sha256-[A-Za-z0-9+/=]+) -->\s*$/;
20
20
  /**
@@ -241,21 +241,5 @@ async function install(opts) {
241
241
  function reloadNotes(skillsDirCreated) {
242
242
  return [skillsDirCreated ? 'Claude Code: 이미 열려 있던 Claude Code 세션에서는 /reload-skills를 한 번 입력하세요 (새로 여는 세션은 필요 없음).' : 'Claude Code: 열려 있는 세션에도 바뀐 스킬이 자동으로 적용됩니다.', 'Helpy Code 데스크톱은 다시 시작하세요.'];
243
243
  }
244
- /** --dry-run: 스킬 폴더를 쓰지 않고 install이 무엇을 할지만 */
245
- function planInstall(opts) {
246
- const dir = skillsDir(opts);
247
- const skills = skillNames(opts.root).map(name => {
248
- const state = inspectSkill(dir, name, opts.version).state;
249
- const action = state === 'missing' ? 'would-install' : state === 'current' ? 'skipped' : state === 'outdated' || opts.force ? 'would-update' : state === 'newer' ? 'newer' : 'kept';
250
- return {
251
- name,
252
- action
253
- };
254
- });
255
- return {
256
- dir,
257
- skills
258
- };
259
- }
260
244
 
261
- export { GUIDE_SKILL, compareVersions, inspectSkill, install, isDotPath, markedSkillNames, planInstall, reloadNotes, removeSkillFiles, renderSkill, skillFiles, skillNames, skillsDir };
245
+ export { GUIDE_SKILL, compareVersions, inspectSkill, install, isDotPath, markedSkillNames, reloadNotes, removeSkillFiles, renderSkill, skillFiles, skillNames, skillsDir };
@@ -15,7 +15,7 @@ export declare function matchesPattern(answerKey: unknown, answer: unknown): boo
15
15
  * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012):
16
16
  * 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
17
17
  * - pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
18
- * - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음, G136)
18
+ * - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음)
19
19
  * - 채점 설정(편집 화면이 저장하는 settings.grading)이 없으면 제출만 받고 `{ null, null }`
20
20
  */
21
21
  export declare function grade(local: LocalGrading | undefined, answer: unknown): GradeResult;
package/es/dev/grading.js CHANGED
@@ -16,7 +16,7 @@ function matchesPattern(answerKey, answer) {
16
16
  * 템플릿 mock(`lib/cdk-mock.js`의 gradeLocally)과 같은 판정이다. 완료 정책은 LXP 설정이라 보지 않는다 (ADR 0012):
17
17
  * 채점 설정이 있으면 채점하고, 없으면 제출만 받는다.
18
18
  * - pattern: 답 문자열 전체를 정규식 하나로 비교 0 / 100
19
- * - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음, G136)
19
+ * - rubric: 흉내 점수 RUBRIC_DEV_SCORE, 통과로 본다 (통과 기준 pass_threshold는 정해지지 않음)
20
20
  * - 채점 설정(편집 화면이 저장하는 settings.grading)이 없으면 제출만 받고 `{ null, null }`
21
21
  */
22
22
  function grade(local, answer) {
@@ -142,7 +142,7 @@ function hostPage(opts) {
142
142
  }
143
143
 
144
144
  // 화면(learn · instructor · edit)은 검사기가 kindModes로 이미 걸러 state.entries에 켠 것만 온다.
145
- // 문제 설명에는 학생 보기만 둔다: 다른 보기가 있는지는 서버 · LXP와 아직 정하지 않았다 (progress G81)
145
+ // 문제 설명에는 학생 보기만 둔다: 다른 보기가 있는지는 서버 · LXP와 아직 정하지 않았다
146
146
  const available = (s) => entryOf(s[2]) && (state.kind !== 'description' || s[0] === 'student');
147
147
  function renderScenarios() {
148
148
  scenariosEl.replaceChildren(...SCENARIOS.filter(available).map(([scenario, label]) => {
@@ -185,7 +185,7 @@ function hostPage(opts) {
185
185
  ? 'settings-saved: 저장했습니다. 다른 보기에서 material.settings로 받습니다 (내용 · 채점 방식 · 답은 .ecdk/settings.json)'
186
186
  : 'settings-saved: 저장 실패 (' + payload.code + ')');
187
187
  return;
188
- // init의 불러오기 상태 (PLAT-5246). loading · ready는 매번 오므로 적지 않고, 실패만 적는다
188
+ // init의 불러오기 상태. loading · ready는 매번 오므로 적지 않고, 실패만 적는다
189
189
  // (LXP는 failed를 받으면 자기 실패 화면을 띄움: reason network · auth · config)
190
190
  case 'status':
191
191
  if (payload.state === 'failed')
@@ -25,10 +25,12 @@ export declare class DevPortError extends Error {
25
25
  /**
26
26
  * 로컬에서 운영과 같은 조건으로 콘텐츠를 띄운다.
27
27
  * - 호스트(localhost): LXP 흉내 화면 + elice-material 흉내 API(/api) + 콘솔 수집
28
- * - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영 콘텐츠 CSP 초안(rules/csp.ts,
29
- * 서버 수정 제안 1번과 같은 값, sandbox allow-scripts allow-same-origin)으로. 콘텐츠는 제 출처(127.0.0.1:<port+1>)로 돌아
30
- * 저장소는 호스트와 따로 쓰고, 제 파일 요청은 같은 출처라 막히지 않는다. 외부 이미지 · 글꼴 · fetch 등은 LXP에서처럼
31
- * 막히고, 막힌 요청은 dev 스크립트가 화면 기록 · 터미널에 "막힌 외부 요청"으로 알린다. LXP 자료 파일 서버처럼 CORS 헤더는 주지 않는다
28
+ * - 콘텐츠(127.0.0.1, 다른 출처): Vite dev 서버(ecdk 플러그인, engines/vite)가 원본을 주고 SDK 등 npm 의존성을 풀어 준다
29
+ * (HMR은 Vite 기본). zip에서 빠지는 파일은 주지 않는다. 운영 콘텐츠 CSP 초안(rules/csp.ts, 서버 수정 제안 1번과 같은 값,
30
+ * sandbox allow-scripts allow-same-origin)으로 응답하고, connect-src에만 Vite HMR 웹소켓(같은 콘텐츠 출처)을 더한다.
31
+ * 콘텐츠는 제 출처(127.0.0.1:<port+1>)로 돌아 저장소는 호스트와 따로 쓰고, 제 파일 요청은 같은 출처라 막히지 않는다.
32
+ * 외부 이미지 · 글꼴 · fetch 등은 LXP에서처럼 막히고, 막힌 요청은 dev 스크립트가 화면 기록 · 터미널에 "막힌 외부 요청"으로
33
+ * 알린다. LXP 자료 파일 서버처럼 CORS 헤더는 주지 않는다
32
34
  * - 원본이 바뀌면 다시 준비 · 검사 → 호스트가 iframe을 다시 띄움
33
35
  */
34
36
  export declare function startDevServer(opts: DevServerOptions): Promise<DevServer>;
package/es/dev/server.js CHANGED
@@ -1,48 +1,20 @@
1
1
  import { watch } from 'node:fs';
2
2
  import { rm, mkdir, writeFile } from 'node:fs/promises';
3
3
  import { createServer } from 'node:http';
4
- import { resolve, extname, join, basename, relative, sep, dirname } from 'node:path';
4
+ import { resolve, join, basename, relative, sep, dirname } from 'node:path';
5
5
  import { loadConfig, loadSavedSettings, savedGrading, SETTINGS_DATA_FILE, PACKAGE_FILE, CONFIG_FILE } from '../core/config.js';
6
6
  import { prepareContent } from '../core/prepare.js';
7
7
  import { projectCheckOptions } from '../core/project-check.js';
8
- import { inlineModuleScripts } from '../core/sandbox.js';
9
8
  import { missingSdkMessage } from '../core/sdk.js';
9
+ import '../engines/vite/plugin.js';
10
+ import { viteDevServer } from '../engines/vite/run.js';
10
11
  import { checkFiles } from '../rules/check.js';
11
12
  import { contentCsp } from '../rules/csp.js';
12
13
  import '../rules/spec.js';
13
14
  import 'fflate';
14
15
  import { hostPage } from './host-page.js';
15
- import { injectDevScript } from './inject.js';
16
16
  import { DEV_MATERIAL_ID, handleMockApi, isTokenScenario, issueToken, createState } from './mock-api.js';
17
17
 
18
- const MIME = {
19
- html: 'text/html; charset=utf-8',
20
- htm: 'text/html; charset=utf-8',
21
- js: 'text/javascript; charset=utf-8',
22
- mjs: 'text/javascript; charset=utf-8',
23
- css: 'text/css; charset=utf-8',
24
- json: 'application/json; charset=utf-8',
25
- svg: 'image/svg+xml',
26
- png: 'image/png',
27
- jpg: 'image/jpeg',
28
- jpeg: 'image/jpeg',
29
- gif: 'image/gif',
30
- webp: 'image/webp',
31
- avif: 'image/avif',
32
- ico: 'image/x-icon',
33
- woff: 'font/woff',
34
- woff2: 'font/woff2',
35
- ttf: 'font/ttf',
36
- otf: 'font/otf',
37
- mp3: 'audio/mpeg',
38
- mp4: 'video/mp4',
39
- webm: 'video/webm',
40
- wasm: 'application/wasm',
41
- txt: 'text/plain; charset=utf-8',
42
- md: 'text/plain; charset=utf-8',
43
- csv: 'text/csv; charset=utf-8',
44
- pdf: 'application/pdf'
45
- };
46
18
  /** 운영 콘텐츠 경로(/s/{exp}.{sig}/materials/{id}/{draft}/…)와 같은 모양. SDK가 여기서 자료 id를 읽는다 */
47
19
  const CONTENT_PREFIX = `/s/dev/materials/${DEV_MATERIAL_ID}/dev/`;
48
20
  function summarize(check) {
@@ -71,25 +43,15 @@ const listen = (server, port) => new Promise((ok, fail) => {
71
43
  server.once('error', fail);
72
44
  server.listen(port, '127.0.0.1', () => ok(server.address().port));
73
45
  });
74
- /** build와 같이 모듈을 묶은 파일. 묶지 못하면 원본을 그대로 주고 이유를 알린다 (LXP에서는 막힐 것) */
75
- async function servedFiles(prepared, log) {
76
- try {
77
- const {
78
- files
79
- } = await inlineModuleScripts(prepared.files);
80
- return new Map(files.map(f => [f.path, f.data]));
81
- } catch (e) {
82
- log(`[dev] ${e.message}`);
83
- return new Map(prepared.files.map(f => [f.path, f.data]));
84
- }
85
- }
86
46
  /**
87
47
  * 로컬에서 운영과 같은 조건으로 콘텐츠를 띄운다.
88
48
  * - 호스트(localhost): LXP 흉내 화면 + elice-material 흉내 API(/api) + 콘솔 수집
89
- * - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영 콘텐츠 CSP 초안(rules/csp.ts,
90
- * 서버 수정 제안 1번과 같은 값, sandbox allow-scripts allow-same-origin)으로. 콘텐츠는 제 출처(127.0.0.1:<port+1>)로 돌아
91
- * 저장소는 호스트와 따로 쓰고, 제 파일 요청은 같은 출처라 막히지 않는다. 외부 이미지 · 글꼴 · fetch 등은 LXP에서처럼
92
- * 막히고, 막힌 요청은 dev 스크립트가 화면 기록 · 터미널에 "막힌 외부 요청"으로 알린다. LXP 자료 파일 서버처럼 CORS 헤더는 주지 않는다
49
+ * - 콘텐츠(127.0.0.1, 다른 출처): Vite dev 서버(ecdk 플러그인, engines/vite)가 원본을 주고 SDK 등 npm 의존성을 풀어 준다
50
+ * (HMR은 Vite 기본). zip에서 빠지는 파일은 주지 않는다. 운영 콘텐츠 CSP 초안(rules/csp.ts, 서버 수정 제안 1번과 같은 값,
51
+ * sandbox allow-scripts allow-same-origin)으로 응답하고, connect-src에만 Vite HMR 웹소켓(같은 콘텐츠 출처)을 더한다.
52
+ * 콘텐츠는 제 출처(127.0.0.1:<port+1>)로 돌아 저장소는 호스트와 따로 쓰고, 제 파일 요청은 같은 출처라 막히지 않는다.
53
+ * 외부 이미지 · 글꼴 · fetch 등은 LXP에서처럼 막히고, 막힌 요청은 dev 스크립트가 화면 기록 · 터미널에 "막힌 외부 요청"으로
54
+ * 알린다. LXP 자료 파일 서버처럼 CORS 헤더는 주지 않는다
93
55
  * - 원본이 바뀌면 다시 준비 · 검사 → 호스트가 iframe을 다시 띄움
94
56
  */
95
57
  async function startDevServer(opts) {
@@ -116,16 +78,16 @@ async function startDevServer(opts) {
116
78
  * (운영은 material_version.settings). 값 검사는 흉내 서버가 한다. 점(.) 폴더라 감시 · zip에서 빠진다
117
79
  */
118
80
  const saveSettings = settings => writeJson(SETTINGS_DATA_FILE, settings);
119
- // SDK를 설치하기 전에도 mock으로는 열린다 (실제 SDK 모드 ?sdk=real만 lib/cdk.js가 없어 실패, 아래에서 알림)
120
- let prepared = await prepareContent(dir, config, {
121
- requireSdk: false
122
- });
81
+ // SDK는 Vite가 node_modules에서 풀어 준다: 설치 전이면 화면 키트가 SDK를 불러오지 못한다
82
+ let prepared = await prepareContent(dir, config);
123
83
  const warnSdk = () => {
124
- if (prepared.sdk.missing) log(`[dev] ${missingSdkMessage()} 그 전에는 mock SDK로만 열립니다 (?sdk=real은 lib/cdk.js가 없어 실패).`);
84
+ if (prepared.sdk.missing) log(`[dev] ${missingSdkMessage()}`);
125
85
  };
126
86
  warnSdk();
127
- let files = await servedFiles(prepared, log);
128
- let check = checkFiles(prepared.files, await projectCheckOptions(dir, config));
87
+ let vite = null;
88
+ let check = checkFiles(prepared.files, await projectCheckOptions(dir, config, {
89
+ publicFiles: prepared.publicFiles
90
+ }));
129
91
  const clients = new Set();
130
92
  let hostOrigin = '';
131
93
  let contentOrigin = '';
@@ -145,12 +107,14 @@ async function startDevServer(opts) {
145
107
  const content = createServer((req, res) => {
146
108
  const url = new URL(req.url ?? '/', 'http://x');
147
109
  // CONTENT_HOST: 콘텐츠 출처, MATERIAL_API: 흉내 API · dev 기록이 있는 호스트 출처, LXP_ORIGINS: 흉내 화면 출처
110
+ // connect-src에는 Vite HMR 웹소켓(콘텐츠 출처의 ws://)만 dev에서 더한다
111
+ const csp = contentCsp({
112
+ contentHost: contentOrigin,
113
+ materialApi: hostOrigin,
114
+ lxpOrigins: hostOrigin
115
+ }).replace(/(connect-src [^;]*)/, `$1 ${contentOrigin.replace(/^http/, 'ws')}`);
148
116
  const headers = {
149
- 'Content-Security-Policy': contentCsp({
150
- contentHost: contentOrigin,
151
- materialApi: hostOrigin,
152
- lxpOrigins: hostOrigin
153
- }),
117
+ 'Content-Security-Policy': csp,
154
118
  'X-Content-Type-Options': 'nosniff',
155
119
  'Referrer-Policy': 'no-referrer',
156
120
  'Cache-Control': 'no-store'
@@ -164,22 +128,16 @@ async function startDevServer(opts) {
164
128
  res.writeHead(404, headers).end('not found');
165
129
  return;
166
130
  }
167
- let path = decodeURIComponent(url.pathname.slice(CONTENT_PREFIX.length));
168
- if (path === '' || path.endsWith('/')) path += 'index.html';
169
- const data = files.get(path);
170
- if (!data) {
171
- log(`[404] ${path} (zip에 없는 파일)`);
172
- res.writeHead(404, headers).end('not found');
131
+ for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
132
+ // Vite dev 서버(ecdk 플러그인): zip에서 빠지는 파일은 404, HTML에는 dev 스크립트를 넣는다
133
+ if (!vite) {
134
+ res.writeHead(503).end('starting');
173
135
  return;
174
136
  }
175
- const ext = extname(path).slice(1).toLowerCase();
176
- const type = MIME[ext] ?? 'application/octet-stream';
177
- const out = ext === 'html' || ext === 'htm' ? injectDevScript(new TextDecoder().decode(data), hostOrigin) : data;
178
- res.writeHead(200, {
179
- ...headers,
180
- 'Content-Type': type
137
+ vite.middlewares(req, res, () => {
138
+ log(`[404] ${url.pathname.slice(CONTENT_PREFIX.length)} (zip에 없는 파일)`);
139
+ res.writeHead(404).end('not found');
181
140
  });
182
- res.end(out);
183
141
  });
184
142
  // 호스트 서버
185
143
  const cors = {
@@ -315,6 +273,18 @@ async function startDevServer(opts) {
315
273
  if (opts.port === undefined && hostPort !== DEFAULT_PORT) log(`[dev] 기본 포트 ${DEFAULT_PORT} · ${DEFAULT_PORT + 1}이 쓰이고 있어 ${hostPort} · ${contentPort}로 열었습니다.`);
316
274
  hostOrigin = `http://localhost:${hostPort}`;
317
275
  contentOrigin = `http://127.0.0.1:${contentPort}`;
276
+ // 콘텐츠: Vite dev 서버 (HMR 웹소켓은 콘텐츠 서버로). 열지 못하면 열어 둔 두 포트를 닫는다
277
+ try {
278
+ vite = await viteDevServer(dir, {
279
+ base: CONTENT_PREFIX,
280
+ httpServer: content,
281
+ devHost: hostOrigin,
282
+ log
283
+ });
284
+ } catch (e) {
285
+ await Promise.all([new Promise(r => host.close(r)), new Promise(r => content.close(r))]);
286
+ throw e;
287
+ }
318
288
  async function reload() {
319
289
  try {
320
290
  config = await loadConfig(dir);
@@ -322,12 +292,11 @@ async function startDevServer(opts) {
322
292
  const saved = await loadSavedSettings(dir);
323
293
  savedGrading(saved);
324
294
  state.settings = saved;
325
- prepared = await prepareContent(dir, config, {
326
- requireSdk: false
327
- });
295
+ prepared = await prepareContent(dir, config);
328
296
  warnSdk();
329
- files = await servedFiles(prepared, log);
330
- check = checkFiles(prepared.files, await projectCheckOptions(dir, config));
297
+ check = checkFiles(prepared.files, await projectCheckOptions(dir, config, {
298
+ publicFiles: prepared.publicFiles
299
+ }));
331
300
  log(summarize(check));
332
301
  const payload = JSON.stringify(snapshot());
333
302
  for (const c of clients) c.write(`event: reload\ndata: ${payload}\n\n`);
@@ -367,6 +336,7 @@ async function startDevServer(opts) {
367
336
  watcher?.close();
368
337
  configWatcher?.close();
369
338
  for (const c of clients) c.end();
339
+ await vite?.close();
370
340
  const closing = Promise.all([new Promise(r => host.close(r)), new Promise(r => content.close(r))]);
371
341
  host.closeAllConnections();
372
342
  content.closeAllConnections();
@@ -1,2 +1,2 @@
1
- /** 3단계(3-2)에서 구현. 엔진 인터페이스는 @eliceio/cdk-cli의 ContentEngine을 따른다. */
2
- export declare const name = "vite";
1
+ export * from './plugin.js';
2
+ export * from './run.js';
@@ -1,4 +1,2 @@
1
- /** 3단계(3-2)에서 구현. 엔진 인터페이스는 @eliceio/cdk-cli의 ContentEngine을 따른다. */
2
- const name = 'vite';
3
-
4
- export { name };
1
+ export { ECDK_PLUGIN_NAME, ecdk, flattenPlugins } from './plugin.js';
2
+ export { viteBuild, viteDevServer } from './run.js';
@@ -0,0 +1,58 @@
1
+ import { type SandboxReport } from '../../core/sandbox.js';
2
+ import { type CheckResult } from '../../rules/index.js';
3
+ import type { Plugin } from 'vite';
4
+ import type { Excluded } from '../../core/collect.js';
5
+ /** Plugin name. `ecdk build` / `ecdk dev` add the plugin only when the Vite config has none with this name */
6
+ export declare const ECDK_PLUGIN_NAME = "ecdk";
7
+ export interface EcdkOptions {
8
+ /** ecdk project folder (where package.json "ecdk" lives). Default: Vite root or the working directory */
9
+ projectDir?: string | undefined;
10
+ }
11
+ /** Build result (printed by `ecdk build`, also its --json output) */
12
+ export interface EcdkBuildOutput {
13
+ ok: boolean;
14
+ outDir: string;
15
+ zip: string | null;
16
+ zipBytes: number;
17
+ files: string[];
18
+ excluded: Excluded[];
19
+ minify: boolean;
20
+ /** HTML pages whose module scripts were inlined */
21
+ sandbox: SandboxReport;
22
+ /** Source files no other file names (candidates to drop, informational) */
23
+ unreferenced: string[];
24
+ /** Same as metadata.json build.digest */
25
+ digest: string;
26
+ check: CheckResult;
27
+ }
28
+ /** Plugin api: the ecdk CLI finds this plugin instance after Vite resolves the config (configResolved) */
29
+ export interface EcdkPluginApi {
30
+ /**
31
+ * Fail the Vite build on check errors (default true, for a plain `vite build`).
32
+ * `ecdk build` sets false and reports `result` itself
33
+ */
34
+ throwOnError: boolean;
35
+ /** `ecdk dev`: host origin for the dev script injected into content HTML (mock API, logs) */
36
+ devHost?: string | undefined;
37
+ /** `ecdk dev`: where dev messages (404 for files left out of the zip) go. Default: the Vite logger */
38
+ log?: ((line: string) => void) | undefined;
39
+ /** Last build result */
40
+ result?: EcdkBuildOutput | undefined;
41
+ }
42
+ /**
43
+ * ecdk Vite plugin. `ecdk build` / `ecdk dev` run Vite with it, and with it in the project's vite.config.*
44
+ * a plain `vite build` produces the same zip (authors can add Vite plugins and options like any Vite project).
45
+ *
46
+ * - config: Vite options from package.json "ecdk" (root, outDir, minify, sourcemap). Every source HTML is an input
47
+ * (multi-page), `base: './'` (relative paths inside the sandbox iframe), output in `<outDir>/content/`
48
+ * - The SDK (@eliceio/cdk) is a package.json dependency bundled like any import; it is never copied as a file (ADR 0010)
49
+ * - generateBundle: copies source files the bundle did not use (metadata.json, commentary, data, images, …),
50
+ * inlines each page's module scripts (core/sandbox.ts) and drops the chunks, stamps metadata.json `build`
51
+ * - Checks (rules) read the sources; size limits read the real zip. On errors no zip is written
52
+ * - writeBundle: `<outDir>/content.zip` (and `this.error` on check errors unless the CLI reports them)
53
+ * - dev (configureServer · transformIndexHtml): files left out of the zip (answers, `.ecdk/`, …) get 404,
54
+ * and under `ecdk dev` the dev script is injected
55
+ */
56
+ export declare function ecdk(options?: EcdkOptions): Plugin;
57
+ /** Flattens Vite config `plugins` (nested arrays, promises, falsy entries) */
58
+ export declare function flattenPlugins(plugins: unknown): Promise<Plugin[]>;