@eliceio/cdk-cli 0.1.0-alpha.7 → 1.0.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.
- package/README.md +64 -57
- package/es/commands/build/index.d.ts +3 -23
- package/es/commands/build/index.js +16 -148
- package/es/commands/doctor/index.d.ts +3 -2
- package/es/commands/doctor/index.js +10 -9
- package/es/commands/validate/index.js +3 -1
- package/es/core/collect.d.ts +1 -1
- package/es/core/collect.js +3 -1
- package/es/core/config.d.ts +2 -2
- package/es/core/config.js +1 -1
- package/es/core/manifest.d.ts +3 -3
- package/es/core/manifest.js +4 -8
- package/es/core/mcp.d.ts +1 -1
- package/es/core/prepare.d.ts +15 -10
- package/es/core/prepare.js +35 -35
- package/es/core/project-check.d.ts +6 -5
- package/es/core/project-check.js +9 -9
- package/es/core/sandbox.d.ts +6 -30
- package/es/core/sandbox.js +32 -109
- package/es/core/sdk.d.ts +7 -18
- package/es/core/sdk.js +8 -38
- package/es/dev/server.d.ts +6 -4
- package/es/dev/server.js +47 -77
- package/es/engines/vite/index.d.ts +2 -2
- package/es/engines/vite/index.js +2 -4
- package/es/engines/vite/plugin.d.ts +58 -0
- package/es/engines/vite/plugin.js +286 -0
- package/es/engines/vite/run.d.ts +15 -0
- package/es/engines/vite/run.js +92 -0
- package/es/rules/check.js +9 -11
- package/es/rules/index.d.ts +1 -1
- package/es/rules/index.js +1 -1
- package/es/rules/types.d.ts +8 -3
- package/es/rules/unused.d.ts +0 -2
- package/es/rules/unused.js +3 -4
- package/es/rules.json.js +1 -1
- package/es/test-packages.d.ts +3 -1
- package/package.json +8 -3
- package/rules.json +9 -3
- package/skills/_shared/always.md +1 -1
- package/skills/elice-content-guide/topics/03-create-the-project.md +1 -1
- package/skills/elice-content-guide/topics/04-rules.md +1 -1
- package/skills/elice-content-guide/topics/07-move-existing-html.md +2 -2
- package/skills/elice-content-guide/topics/08-fix-check-errors.md +21 -21
- package/skills/elice-content-guide/topics/10-build.md +1 -1
- package/templates/_shared/lib/elice-content.js +8 -12
- package/templates/blank/README.md +2 -3
- package/templates/quiz/README.md +2 -3
- package/es/core/minify.d.ts +0 -18
- package/es/core/minify.js +0 -122
- package/es/engines/static/index.d.ts +0 -3
- package/es/engines/static/index.js +0 -11
- package/es/engines/types.d.ts +0 -12
package/es/core/sdk.js
CHANGED
|
@@ -2,15 +2,14 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import { join, resolve, dirname } from 'node:path';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* SDK(@eliceio/cdk)는 프로젝트 package.json 의존성이다 (ADR 0010
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* SDK(@eliceio/cdk)는 프로젝트 package.json 의존성이다 (ADR 0010). 화면 키트(lib/elice-content.js)가
|
|
6
|
+
* `import('@eliceio/cdk')`로 부르고, ecdk build(Vite)가 node_modules에서 찾아 화면 코드와 함께 번들로 묶는다.
|
|
7
|
+
* SDK 파일을 zip에 따로 넣거나 복사하지 않는다. metadata.json build.sdk는 설치된 패키지 버전
|
|
8
|
+
* (node_modules/@eliceio/cdk/package.json).
|
|
8
9
|
*/
|
|
9
10
|
const SDK_PACKAGE = '@eliceio/cdk';
|
|
10
|
-
/**
|
|
11
|
-
const
|
|
12
|
-
/** 설치된 SDK 안의 UMD 빌드 */
|
|
13
|
-
const SDK_UMD = 'umd/index.js';
|
|
11
|
+
/** 옛 방식의 SDK 복사본 (원본에 있으면 sdk.lib-copy 오류, zip에는 넣지 않는다) */
|
|
12
|
+
const LEGACY_SDK_COPY = 'lib/cdk.js';
|
|
14
13
|
const INSTALL_COMMAND = 'npm install';
|
|
15
14
|
const UPDATE_COMMAND = `npm update ${SDK_PACKAGE}`;
|
|
16
15
|
async function readJson(path) {
|
|
@@ -49,10 +48,7 @@ function declaredSdkRange(pkg) {
|
|
|
49
48
|
}
|
|
50
49
|
return undefined;
|
|
51
50
|
}
|
|
52
|
-
/**
|
|
53
|
-
* 프로젝트가 SDK를 패키지로 쓰는지와 설치 상태. package.json에 @eliceio/cdk가 없으면 null
|
|
54
|
-
* (옛 lib/cdk.js 복사본 프로젝트이거나 SDK를 쓰지 않는 자료: build는 원본 그대로)
|
|
55
|
-
*/
|
|
51
|
+
/** 프로젝트가 SDK를 패키지로 쓰는지와 설치 상태. package.json에 @eliceio/cdk가 없으면 null (SDK를 쓰지 않는 자료이거나 옛 프로젝트) */
|
|
56
52
|
async function readProjectSdk(projectDir) {
|
|
57
53
|
const range = declaredSdkRange(await readJson(join(projectDir, 'package.json')));
|
|
58
54
|
if (range === undefined) return null;
|
|
@@ -65,31 +61,5 @@ async function readProjectSdk(projectDir) {
|
|
|
65
61
|
function missingSdkMessage() {
|
|
66
62
|
return `${SDK_PACKAGE} 패키지를 찾지 못했습니다 (node_modules에 없음). 프로젝트 폴더에서 ${INSTALL_COMMAND}을 실행해 주세요.`;
|
|
67
63
|
}
|
|
68
|
-
/**
|
|
69
|
-
* zip lib/cdk.js 머리말. build.sdk는 이 머리말에서 읽는다 (core/manifest.ts).
|
|
70
|
-
* SDK는 LXP 화면과 postMessage(설정 저장 결과 · 페이지 이동)로 이야기하므로 두 규칙을 이 파일에서만 끈다.
|
|
71
|
-
* 두 규칙은 client 검사라 서버 업로드 검사와는 상관없다
|
|
72
|
-
*/
|
|
73
|
-
function sdkHeader(version) {
|
|
74
|
-
return [`/* ${SDK_PACKAGE} ${version} — UMD. Added by ecdk build from node_modules/${SDK_PACKAGE}; do not edit. */`, '// ecdk-ignore-next-line api.parent-access sec.postmessage-wildcard', ''].join('\n');
|
|
75
|
-
}
|
|
76
|
-
/** 설치된 SDK의 UMD 빌드에 머리말을 붙인 zip 파일 lib/cdk.js */
|
|
77
|
-
async function sdkZipFile(sdk) {
|
|
78
|
-
const umd = join(sdk.dir, ...SDK_UMD.split('/'));
|
|
79
|
-
let data;
|
|
80
|
-
try {
|
|
81
|
-
data = new Uint8Array(await readFile(umd));
|
|
82
|
-
} catch {
|
|
83
|
-
throw new Error(`${SDK_PACKAGE} ${sdk.version}에 UMD 빌드(${SDK_UMD})가 없습니다. ${INSTALL_COMMAND}으로 다시 설치해 주세요.`);
|
|
84
|
-
}
|
|
85
|
-
const head = new TextEncoder().encode(sdkHeader(sdk.version));
|
|
86
|
-
const joined = new Uint8Array(head.byteLength + data.byteLength);
|
|
87
|
-
joined.set(head);
|
|
88
|
-
joined.set(data, head.byteLength);
|
|
89
|
-
return {
|
|
90
|
-
path: SDK_ZIP_PATH,
|
|
91
|
-
data: joined
|
|
92
|
-
};
|
|
93
|
-
}
|
|
94
64
|
|
|
95
|
-
export { INSTALL_COMMAND,
|
|
65
|
+
export { INSTALL_COMMAND, LEGACY_SDK_COPY, SDK_PACKAGE, UPDATE_COMMAND, declaredSdkRange, missingSdkMessage, readProjectSdk };
|
package/es/dev/server.d.ts
CHANGED
|
@@ -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, 다른 출처):
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
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,
|
|
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, 다른 출처):
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
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
|
|
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()}
|
|
84
|
+
if (prepared.sdk.missing) log(`[dev] ${missingSdkMessage()}`);
|
|
125
85
|
};
|
|
126
86
|
warnSdk();
|
|
127
|
-
let
|
|
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':
|
|
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
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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
|
-
|
|
330
|
-
|
|
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
|
-
|
|
2
|
-
export
|
|
1
|
+
export * from './plugin.js';
|
|
2
|
+
export * from './run.js';
|
package/es/engines/vite/index.js
CHANGED
|
@@ -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[]>;
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { mkdir, writeFile, rm } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve, dirname } from 'node:path';
|
|
3
|
+
import { formatIssues } from '../../commands/validate/index.js';
|
|
4
|
+
import { loadConfig, legacyGradingTypesWarning, CONFIG_FILE, legacyCompletionWarning } from '../../core/config.js';
|
|
5
|
+
import { contentDigest } from '../../core/manifest.js';
|
|
6
|
+
import { prepareContent, PUBLIC_DIR } from '../../core/prepare.js';
|
|
7
|
+
import { projectCheckOptions } from '../../core/project-check.js';
|
|
8
|
+
import { inlineModuleScripts } from '../../core/sandbox.js';
|
|
9
|
+
import { missingSdkMessage } from '../../core/sdk.js';
|
|
10
|
+
import { createZip } from '../../core/zip.js';
|
|
11
|
+
import { injectDevScript } from '../../dev/inject.js';
|
|
12
|
+
import { checkFiles } from '../../rules/check.js';
|
|
13
|
+
import { rules } from '../../rules/spec.js';
|
|
14
|
+
import { stripCompletionPolicy } from '../../rules/manifest.js';
|
|
15
|
+
import { findUnreferenced } from '../../rules/unused.js';
|
|
16
|
+
import 'fflate';
|
|
17
|
+
|
|
18
|
+
/** Plugin name. `ecdk build` / `ecdk dev` add the plugin only when the Vite config has none with this name */
|
|
19
|
+
const ECDK_PLUGIN_NAME = 'ecdk';
|
|
20
|
+
const encoder = new TextEncoder();
|
|
21
|
+
const decoder = new TextDecoder();
|
|
22
|
+
/**
|
|
23
|
+
* Adds values to metadata.json `build` (also an authored one). Legacy completion-policy fields are dropped from the zip
|
|
24
|
+
* (completion policy is an LXP setting, ADR 0012; leftovers are reported by manifest.completion-policies-ignored).
|
|
25
|
+
* Malformed JSON is left as is for the checks to report
|
|
26
|
+
*/
|
|
27
|
+
function withBuildStamp(files, stamp) {
|
|
28
|
+
return files.map(f => {
|
|
29
|
+
if (f.path !== rules.manifest.file) return f;
|
|
30
|
+
try {
|
|
31
|
+
const raw = JSON.parse(decoder.decode(f.data));
|
|
32
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return f;
|
|
33
|
+
const next = {
|
|
34
|
+
...stripCompletionPolicy(raw),
|
|
35
|
+
build: {
|
|
36
|
+
...raw.build,
|
|
37
|
+
...stamp
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
...f,
|
|
42
|
+
data: encoder.encode(`${JSON.stringify(next, null, 2)}\n`)
|
|
43
|
+
};
|
|
44
|
+
} catch {
|
|
45
|
+
return f;
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/** Source checks + limits against the real zip + legacy config warnings */
|
|
50
|
+
async function checkBuild(projectDir, config, prepared, files, zipBytes) {
|
|
51
|
+
// Checks read the sources before bundling: bundling/minifying drops ecdk-ignore comments, shifts line numbers
|
|
52
|
+
// and would scan the bundled SDK. Size limits use the real zip. Project checks also report legacy files and
|
|
53
|
+
// the SDK copy (.ecdk is never read)
|
|
54
|
+
const check = checkFiles(prepared.files, await projectCheckOptions(projectDir, config, {
|
|
55
|
+
publicFiles: prepared.publicFiles,
|
|
56
|
+
zipBytes
|
|
57
|
+
}));
|
|
58
|
+
const realCount = files.length;
|
|
59
|
+
if (realCount > rules.limits.maxFiles && !check.issues.some(i => i.id === 'limit.file-count')) {
|
|
60
|
+
check.issues.unshift({
|
|
61
|
+
id: 'limit.file-count',
|
|
62
|
+
level: 'error',
|
|
63
|
+
message: `결과물 파일이 ${realCount}개라 한도 ${rules.limits.maxFiles}개를 넘습니다. 파일을 줄여 주세요.`
|
|
64
|
+
});
|
|
65
|
+
check.ok = false;
|
|
66
|
+
}
|
|
67
|
+
// Legacy elice.config.json gradingTypes: not migrated, only asked to remove (ADR 0008 · 0009)
|
|
68
|
+
const legacy = legacyGradingTypesWarning(config);
|
|
69
|
+
if (legacy) check.issues.push({
|
|
70
|
+
id: 'manifest.grading-types',
|
|
71
|
+
level: 'warn',
|
|
72
|
+
message: legacy,
|
|
73
|
+
path: CONFIG_FILE
|
|
74
|
+
});
|
|
75
|
+
// Legacy elice.config.json completion policies: not migrated (LXP setting, ADR 0012)
|
|
76
|
+
const legacyCompletion = legacyCompletionWarning(config);
|
|
77
|
+
if (legacyCompletion) check.issues.push({
|
|
78
|
+
id: 'manifest.completion-policies-ignored',
|
|
79
|
+
level: 'warn',
|
|
80
|
+
message: legacyCompletion,
|
|
81
|
+
path: CONFIG_FILE
|
|
82
|
+
});
|
|
83
|
+
return check;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* ecdk Vite plugin. `ecdk build` / `ecdk dev` run Vite with it, and with it in the project's vite.config.*
|
|
87
|
+
* a plain `vite build` produces the same zip (authors can add Vite plugins and options like any Vite project).
|
|
88
|
+
*
|
|
89
|
+
* - config: Vite options from package.json "ecdk" (root, outDir, minify, sourcemap). Every source HTML is an input
|
|
90
|
+
* (multi-page), `base: './'` (relative paths inside the sandbox iframe), output in `<outDir>/content/`
|
|
91
|
+
* - The SDK (@eliceio/cdk) is a package.json dependency bundled like any import; it is never copied as a file (ADR 0010)
|
|
92
|
+
* - generateBundle: copies source files the bundle did not use (metadata.json, commentary, data, images, …),
|
|
93
|
+
* inlines each page's module scripts (core/sandbox.ts) and drops the chunks, stamps metadata.json `build`
|
|
94
|
+
* - Checks (rules) read the sources; size limits read the real zip. On errors no zip is written
|
|
95
|
+
* - writeBundle: `<outDir>/content.zip` (and `this.error` on check errors unless the CLI reports them)
|
|
96
|
+
* - dev (configureServer · transformIndexHtml): files left out of the zip (answers, `.ecdk/`, …) get 404,
|
|
97
|
+
* and under `ecdk dev` the dev script is injected
|
|
98
|
+
*/
|
|
99
|
+
function ecdk(options = {}) {
|
|
100
|
+
const api = {
|
|
101
|
+
throwOnError: true
|
|
102
|
+
};
|
|
103
|
+
let projectDir = '';
|
|
104
|
+
let config;
|
|
105
|
+
let prepared;
|
|
106
|
+
let isBuild = false;
|
|
107
|
+
let pendingZip = null;
|
|
108
|
+
async function prepare() {
|
|
109
|
+
config = await loadConfig(projectDir);
|
|
110
|
+
prepared = await prepareContent(projectDir, config);
|
|
111
|
+
return prepared;
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
name: ECDK_PLUGIN_NAME,
|
|
115
|
+
enforce: 'post',
|
|
116
|
+
api,
|
|
117
|
+
async config(user, env) {
|
|
118
|
+
isBuild = env.command === 'build';
|
|
119
|
+
projectDir = resolve(options.projectDir ?? user.root ?? process.cwd());
|
|
120
|
+
const p = await prepare();
|
|
121
|
+
const pages = p.files.filter(f => /\.html?$/i.test(f.path) && !p.publicFiles.has(f.path)).map(f => f.path);
|
|
122
|
+
if (isBuild && p.sdk.missing) throw new Error(missingSdkMessage());
|
|
123
|
+
return {
|
|
124
|
+
root: p.srcDir,
|
|
125
|
+
// Content opens under the material URL in a sandbox iframe, so output uses relative paths
|
|
126
|
+
// (ecdk dev passes its own content base)
|
|
127
|
+
...(isBuild ? {
|
|
128
|
+
base: './'
|
|
129
|
+
} : {}),
|
|
130
|
+
appType: 'mpa',
|
|
131
|
+
cacheDir: join(projectDir, 'node_modules', '.vite'),
|
|
132
|
+
build: {
|
|
133
|
+
outDir: join(p.outDir, 'content'),
|
|
134
|
+
emptyOutDir: true,
|
|
135
|
+
minify: config.minify !== false,
|
|
136
|
+
cssMinify: config.minify !== false,
|
|
137
|
+
// Chunks are inlined into the HTML, so their maps are inline too and chained there (core/sandbox.ts)
|
|
138
|
+
sourcemap: config.sourcemap === true ? 'inline' : false,
|
|
139
|
+
// modulepreload is a CORS request, blocked when the LXP content origin is null; chunks are inlined anyway
|
|
140
|
+
modulePreload: false,
|
|
141
|
+
reportCompressedSize: false,
|
|
142
|
+
// public/ files go into the output from generateBundle, following the zip rules (answers etc. excluded)
|
|
143
|
+
copyPublicDir: false,
|
|
144
|
+
rolldownOptions: {
|
|
145
|
+
input: Object.fromEntries(pages.map(page => [page, join(p.srcDir, page)])),
|
|
146
|
+
// Chunks are inlined and removed, but their names stay in the HTML (data-ecdk-bundle) and the digest:
|
|
147
|
+
// chunk hashes depend on the absolute project path, so chunks get stable names for reproducible zips
|
|
148
|
+
output: {
|
|
149
|
+
entryFileNames: 'assets/[name].js',
|
|
150
|
+
chunkFileNames: 'assets/[name].js'
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
async buildStart() {
|
|
157
|
+
if (!isBuild) return;
|
|
158
|
+
pendingZip = null;
|
|
159
|
+
api.result = undefined;
|
|
160
|
+
await rm(join(prepared.outDir, 'content.zip'), {
|
|
161
|
+
force: true
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
generateBundle: {
|
|
165
|
+
order: 'post',
|
|
166
|
+
async handler(_options, bundle) {
|
|
167
|
+
const output = [];
|
|
168
|
+
for (const item of Object.values(bundle)) output.push({
|
|
169
|
+
path: item.fileName,
|
|
170
|
+
data: item.type === 'chunk' ? encoder.encode(item.code) : typeof item.source === 'string' ? encoder.encode(item.source) : item.source
|
|
171
|
+
});
|
|
172
|
+
// Besides the bundle: public/ files as they are, and the files metadata.json names (commentary)
|
|
173
|
+
const manifest = prepared.files.find(f => f.path === rules.manifest.file);
|
|
174
|
+
let commentary;
|
|
175
|
+
try {
|
|
176
|
+
commentary = manifest ? JSON.parse(decoder.decode(manifest.data)).commentary : undefined;
|
|
177
|
+
} catch {
|
|
178
|
+
// Malformed metadata.json is reported by the checks
|
|
179
|
+
}
|
|
180
|
+
const emitted = new Set(output.map(f => f.path));
|
|
181
|
+
for (const f of prepared.files) if (!emitted.has(f.path) && (prepared.publicFiles.has(f.path) || f.path === commentary)) output.push(f);
|
|
182
|
+
// Inline each page's module scripts (chunks) so pages load even when the LXP content origin is null
|
|
183
|
+
const sandboxed = await inlineModuleScripts(output, {
|
|
184
|
+
minify: config.minify !== false,
|
|
185
|
+
sourcemap: config.sourcemap === true
|
|
186
|
+
});
|
|
187
|
+
const chunks = new Set(Object.values(bundle).filter(item => item.type === 'chunk').map(item => item.fileName));
|
|
188
|
+
const content = sandboxed.files.filter(f => !chunks.has(f.path));
|
|
189
|
+
if (manifest) content.push(manifest);
|
|
190
|
+
// metadata.json build gets the minify flag and the digest of the final files (metadata.json excluded)
|
|
191
|
+
const digest = contentDigest(content);
|
|
192
|
+
const files = withBuildStamp(content, {
|
|
193
|
+
...(config.minify !== false ? {
|
|
194
|
+
minify: true
|
|
195
|
+
} : {}),
|
|
196
|
+
digest
|
|
197
|
+
});
|
|
198
|
+
// Replace the Vite bundle with the final output: update emitted assets in place,
|
|
199
|
+
// drop the inlined chunks, and emit the copied source files
|
|
200
|
+
const finalPaths = new Set(files.map(f => f.path));
|
|
201
|
+
for (const name of Object.keys(bundle)) if (!finalPaths.has(name)) delete bundle[name];
|
|
202
|
+
for (const f of files) {
|
|
203
|
+
const item = bundle[f.path];
|
|
204
|
+
if (item?.type === 'asset') item.source = f.data;else this.emitFile({
|
|
205
|
+
type: 'asset',
|
|
206
|
+
fileName: f.path,
|
|
207
|
+
source: f.data
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
const zip = createZip(files);
|
|
211
|
+
const check = await checkBuild(projectDir, config, prepared, files, zip.byteLength);
|
|
212
|
+
pendingZip = zip;
|
|
213
|
+
api.result = {
|
|
214
|
+
ok: check.ok,
|
|
215
|
+
outDir: prepared.outDir,
|
|
216
|
+
zip: check.ok ? join(prepared.outDir, 'content.zip') : null,
|
|
217
|
+
zipBytes: zip.byteLength,
|
|
218
|
+
files: files.map(f => f.path),
|
|
219
|
+
excluded: prepared.excluded,
|
|
220
|
+
minify: config.minify !== false,
|
|
221
|
+
sandbox: sandboxed.report,
|
|
222
|
+
unreferenced: findUnreferenced(prepared.files, check.manifest),
|
|
223
|
+
digest,
|
|
224
|
+
check
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
async writeBundle() {
|
|
229
|
+
const result = api.result;
|
|
230
|
+
if (!result || !pendingZip) return;
|
|
231
|
+
if (result.ok && result.zip) {
|
|
232
|
+
await mkdir(dirname(result.zip), {
|
|
233
|
+
recursive: true
|
|
234
|
+
});
|
|
235
|
+
await writeFile(result.zip, pendingZip);
|
|
236
|
+
}
|
|
237
|
+
if (!api.throwOnError) return;
|
|
238
|
+
for (const issue of result.check.issues.filter(i => i.level !== 'error')) this.warn(`${issue.id}${issue.path ? ` ${issue.path}` : ''}: ${issue.message}`);
|
|
239
|
+
if (!result.ok) this.error(['검사 오류가 있어 zip을 만들지 않았습니다.', ...formatIssues(result.check)].join('\n'));
|
|
240
|
+
},
|
|
241
|
+
configureServer(server) {
|
|
242
|
+
// Files left out of the zip (answers, secrets, .ecdk, project files) are not served in dev either
|
|
243
|
+
let current = Promise.resolve(prepared);
|
|
244
|
+
server.watcher.on('all', () => {
|
|
245
|
+
current = prepare().catch(() => prepared);
|
|
246
|
+
});
|
|
247
|
+
const guard = (req, res, next) => {
|
|
248
|
+
const base = server.config.base;
|
|
249
|
+
const url = (req.url ?? '/').replace(/[?#].*$/, '');
|
|
250
|
+
if (!url.startsWith(base)) return next();
|
|
251
|
+
let path;
|
|
252
|
+
try {
|
|
253
|
+
path = decodeURIComponent(url.slice(base.length));
|
|
254
|
+
} catch {
|
|
255
|
+
return next();
|
|
256
|
+
}
|
|
257
|
+
// Vite internals (@vite/client, @fs, node_modules/.vite, …) pass through
|
|
258
|
+
if (path.startsWith('@') || path.startsWith('node_modules/')) return next();
|
|
259
|
+
void current.then(p => {
|
|
260
|
+
const hidden = path.startsWith('.') || [path, PUBLIC_DIR + path].some(at => p.excluded.some(e => at === e.path || at.startsWith(`${e.path}/`)));
|
|
261
|
+
if (!hidden) return next();
|
|
262
|
+
const line = `[404] ${path} (zip에 없는 파일)`;
|
|
263
|
+
if (api.log) api.log(line);else server.config.logger.warn(line);
|
|
264
|
+
res.statusCode = 404;
|
|
265
|
+
res.end('not found');
|
|
266
|
+
}, next);
|
|
267
|
+
};
|
|
268
|
+
server.middlewares.use(guard);
|
|
269
|
+
},
|
|
270
|
+
transformIndexHtml: {
|
|
271
|
+
order: 'post',
|
|
272
|
+
handler(html) {
|
|
273
|
+
// ecdk dev only: mock API address, console forwarding, CSP reports (never in the zip)
|
|
274
|
+
return !isBuild && api.devHost ? injectDevScript(html, api.devHost) : html;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
/** Flattens Vite config `plugins` (nested arrays, promises, falsy entries) */
|
|
280
|
+
async function flattenPlugins(plugins) {
|
|
281
|
+
const value = await plugins;
|
|
282
|
+
if (Array.isArray(value)) return (await Promise.all(value.map(flattenPlugins))).flat();
|
|
283
|
+
return value && typeof value === 'object' && 'name' in value ? [value] : [];
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export { ECDK_PLUGIN_NAME, ecdk, flattenPlugins };
|