@eliceio/cdk-cli 1.2.1 → 1.3.0-contenttypes.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +59 -50
  2. package/es/cli.js +11 -2
  3. package/es/commands/build/index.js +12 -0
  4. package/es/commands/create/index.js +1 -0
  5. package/es/commands/create/scaffold.d.ts +2 -2
  6. package/es/commands/create/scaffold.js +3 -3
  7. package/es/commands/dev/index.d.ts +10 -1
  8. package/es/commands/dev/index.js +47 -7
  9. package/es/core/config.d.ts +20 -9
  10. package/es/core/config.js +53 -12
  11. package/es/core/project-check.d.ts +3 -2
  12. package/es/core/project-check.js +14 -3
  13. package/es/core/regex.d.ts +11 -0
  14. package/es/core/regex.js +41 -0
  15. package/es/core/sandbox.d.ts +26 -0
  16. package/es/core/sandbox.js +240 -30
  17. package/es/dev/check.d.ts +30 -0
  18. package/es/dev/check.js +224 -34
  19. package/es/dev/grading.d.ts +20 -1
  20. package/es/dev/grading.js +38 -7
  21. package/es/dev/host-page.js +1 -1
  22. package/es/dev/mock-api.d.ts +3 -1
  23. package/es/dev/mock-api.js +20 -11
  24. package/es/engines/vite/index.js +1 -1
  25. package/es/engines/vite/plugin.d.ts +2 -0
  26. package/es/engines/vite/plugin.js +33 -5
  27. package/es/rules/answers.d.ts +13 -0
  28. package/es/rules/answers.js +94 -0
  29. package/es/rules/check.js +70 -1
  30. package/es/rules/index.d.ts +1 -0
  31. package/es/rules/index.js +1 -0
  32. package/es/rules/size.d.ts +31 -0
  33. package/es/rules/size.js +58 -0
  34. package/es/rules/types.d.ts +12 -0
  35. package/es/rules.json.js +2 -2
  36. package/package.json +2 -2
  37. package/rules.json +32 -3
  38. package/skills/_shared/always.md +3 -3
  39. package/skills/_shared/references/00-what-the-person-decides.md +1 -1
  40. package/skills/_shared/references/02-design-the-material.md +10 -7
  41. package/skills/_shared/references/03-create-the-project.md +2 -1
  42. package/skills/_shared/references/05-screen-code.md +49 -22
  43. package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
  44. package/skills/_shared/references/08-fix-check-errors.md +23 -22
  45. package/skills/_shared/references/09-check.md +7 -6
  46. package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
  47. package/skills/_shared/references/13-edit-screen-design.md +122 -0
  48. package/skills/_shared/references/14-layouts.md +96 -0
  49. package/skills/elice-content-check/SKILL.md +2 -2
  50. package/skills/elice-content-create/SKILL.md +1 -1
  51. package/skills/elice-content-migrate/SKILL.md +1 -1
  52. package/templates/_shared/lib/cdk-mock.d.ts +30 -3
  53. package/templates/_shared/lib/cdk-mock.js +88 -15
  54. package/templates/_shared/lib/elice-content-editor.js +89 -58
  55. package/templates/_shared/lib/elice-content.css +1313 -126
  56. package/templates/_shared/lib/elice-content.d.ts +162 -23
  57. package/templates/_shared/lib/elice-content.js +863 -82
  58. package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
  59. package/templates/_shared/lib/icons/empty-content.js +11 -0
  60. package/templates/_shared/lib/icons/file-video.d.ts +2 -0
  61. package/templates/_shared/lib/icons/file-video.js +11 -0
  62. package/templates/_shared/lib/icons/file.d.ts +2 -0
  63. package/templates/_shared/lib/icons/file.js +11 -0
  64. package/templates/blank/README.md +5 -3
  65. package/templates/blank/edit.html +8 -2
  66. package/templates/blank/index.html +6 -1
  67. package/templates/blank/instructor.html +6 -1
  68. package/templates/blank/template.json +1 -1
  69. package/templates/quiz/README.md +28 -12
  70. package/templates/quiz/core/behaviors.d.ts +13 -7
  71. package/templates/quiz/core/behaviors.js +36 -51
  72. package/templates/quiz/core/editor.d.ts +10 -0
  73. package/templates/quiz/core/editor.js +334 -8
  74. package/templates/quiz/core/markdown.d.ts +4 -0
  75. package/templates/quiz/core/markdown.js +65 -11
  76. package/templates/quiz/core/model.d.ts +34 -1
  77. package/templates/quiz/core/model.js +86 -5
  78. package/templates/quiz/core/rich-text.d.ts +19 -0
  79. package/templates/quiz/core/rich-text.js +521 -0
  80. package/templates/quiz/edit.html +12 -3
  81. package/templates/quiz/index.html +12 -3
  82. package/templates/quiz/screens/edit.js +217 -48
  83. package/templates/quiz/screens/learn.js +90 -14
  84. package/templates/quiz/styles.css +840 -678
  85. package/templates/quiz/template.json +9 -2
  86. package/templates/quiz/ui/templates/edit.d.ts +18 -5
  87. package/templates/quiz/ui/templates/edit.js +309 -71
  88. package/templates/quiz/ui/templates/group.js +19 -8
  89. package/templates/quiz/ui/templates/order.js +25 -24
  90. package/templates/quiz/ui/templates/page.js +19 -8
  91. package/templates/quiz/ui/templates/question.js +2 -2
  92. package/templates/quiz/ui/texts.js +72 -25
  93. package/templates/quiz/ui/theme.css +8 -9
  94. package/templates/steps/README.md +77 -0
  95. package/templates/steps/commentary.txt +7 -0
  96. package/templates/steps/edit.html +21 -0
  97. package/templates/steps/gitignore +4 -0
  98. package/templates/steps/index.html +69 -0
  99. package/templates/steps/metadata.json +9 -0
  100. package/templates/steps/package.json +13 -0
  101. package/templates/steps/screens/edit.js +32 -0
  102. package/templates/steps/screens/learn.js +108 -0
  103. package/templates/steps/styles.css +54 -0
  104. package/templates/steps/template.json +6 -0
@@ -3,6 +3,7 @@ import 'fflate';
3
3
  import { rules } from '../rules/spec.js';
4
4
  import { resolveRef } from '../rules/path.js';
5
5
  import { classifyRef } from '../rules/refs.js';
6
+ import { screenSizes, LAZY_FILE_MARK } from '../rules/size.js';
6
7
 
7
8
  /**
8
9
  * LXP는 자료를 콘텐츠마다 다른 출처의 sandbox iframe(`allow-scripts allow-same-origin`)에서 연다.
@@ -18,28 +19,61 @@ import { classifyRef } from '../rules/refs.js';
18
19
  * (결과물 안 파일만 묶음. `import.meta.url`은 원래 파일 주소로 바꿔 상대경로 계산이 그대로 맞게).
19
20
  * - zip 안 JSON(metadata.json 제외, 작성자가 넣은 데이터 파일)을 페이지에 넣고 `fetch`가 그 주소를 받으면 넣어 둔 내용을 돌려준다.
20
21
  * 묶어 넣은 chunk 파일은 플러그인이 결과물에서 뺀다.
22
+ *
23
+ * 나중에 받는 파일 (Vite chunk 관계를 넘겨받을 때, `splitLazyChunks`):
24
+ * 화면을 열 때 실행되지 않는 chunk(동적 `import()`로만 닿는 것)가 모두 합쳐 `LAZY_MIN_BYTES` 이상이면 HTML에 넣지 않고
25
+ * chunk마다 일반 스크립트 파일로 낸다. `import()`는 그 파일을 `<script src>`(CORS 없음, CSP script-src의 콘텐츠 호스트)로
26
+ * 받아 실행하는 함수(`__ecdk_load`)로 바뀐다. 그래서 문서 화면은 쓰는 쪽(PDF · PPTX)의 라이브러리만 받는다.
27
+ * - 나중에 받는 chunk는 iife로 묶고, 다른 chunk를 부르는 import는 페이지의 모듈 목록(`__ecdk_lazy`)에서 꺼낸다:
28
+ * 같은 chunk가 두 번 실행되지 않는다 (화면에 넣은 chunk도 목록에 올려 같은 것을 씀).
29
+ * - 안 되는 경우는 나누지 않고 지금처럼 HTML에 다 넣는다 (`SandboxScreen.lazySkipped`): 나중에 받는 chunk에
30
+ * top-level await가 있음(일반 스크립트로 못 냄) · chunk끼리 서로 부름(순환) · 묶기 실패.
21
31
  */
22
32
  const encoder = new TextEncoder();
23
33
  const decoder = new TextDecoder();
24
34
  const MODULE_SCRIPT = /<script\b([^>]*)>\s*<\/script\s*>/gi;
25
35
  /** build가 묶어 넣은 모듈 스크립트 표시 (검사가 본문을 건너뜀) */
26
36
  const BUNDLE_ATTR = 'data-ecdk-bundle';
37
+ /** 화면을 열 때 실행되지 않는 chunk가 합쳐 이만큼 이상이면 따로 파일로 낸다 (그보다 작으면 요청을 늘리지 않고 HTML에) */
38
+ const LAZY_MIN_BYTES = 200 * 1024;
39
+ /** esbuild가 그대로 남기는 import() 주소 표시. 묶은 뒤 `__ecdk_load(경로)`로 바꾼다 */
40
+ const LAZY_PREFIX = '__ecdk_lazy__:';
41
+ const LAZY_IMPORT = /\bimport\(\s*(["'`])__ecdk_lazy__:([^"'`]+)\1\s*\)/g;
42
+ const VIRTUAL = 'ecdk-virtual';
43
+ const CHUNK_REF = 'ecdk-chunk';
27
44
  function attr(attrs, name) {
28
45
  const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(attrs);
29
46
  return m ? m[1] ?? m[2] ?? m[3] : undefined;
30
47
  }
31
48
  /** HTML 안에 넣어도 태그가 끝나지 않게 */
32
49
  const escapeInline = code => code.replace(/<\/(script)/gi, '<\\/$1');
33
- /** zip 안 파일만 읽는 esbuild 플러그인. zip 밖(외부 주소 · 패키지 이름)은 오류 */
34
50
  /** 페이지 폴더에서 zip 최상위로 올라가는 ../ (하위 폴더 페이지는 깊이만큼) */
35
51
  const upFrom = page => '../'.repeat(page.split('/').length - 1);
36
- function zipFiles(byPath, page) {
52
+ const json = value => JSON.stringify(value);
53
+ /** zip 안 파일만 읽는 esbuild 플러그인. zip 밖(외부 주소 · 패키지 이름)은 오류 */
54
+ function zipFiles(byPath, opts) {
37
55
  return {
38
56
  name: 'ecdk-zip',
39
57
  setup(b) {
40
58
  b.onResolve({
41
59
  filter: /.*/
42
60
  }, args => {
61
+ // 가상 모듈: 페이지 진입(모듈 목록 등록 + 화면 진입 파일)과 그 안의 zip 경로
62
+ if (args.path.startsWith(`${VIRTUAL}:`)) return {
63
+ path: args.path,
64
+ namespace: VIRTUAL
65
+ };
66
+ if (args.namespace === VIRTUAL) {
67
+ if (!byPath.has(args.path)) return {
68
+ errors: [{
69
+ text: `파일이 없습니다: ${args.path}`
70
+ }]
71
+ };
72
+ return opts.redirect?.(args.path, args.kind) ?? {
73
+ path: args.path,
74
+ namespace: 'zip'
75
+ };
76
+ }
43
77
  // 진입 파일은 zip 경로로 넘긴다. 실행 폴더에 같은 이름의 파일이 있으면 esbuild가 앞에 ./를 붙여 넘기므로 뗀다
44
78
  if (args.kind === 'entry-point') {
45
79
  const path = args.path.replace(/^\.\//, '');
@@ -70,11 +104,26 @@ function zipFiles(byPath, page) {
70
104
  text: `파일이 없습니다: ${args.path} (${args.importer}에서)`
71
105
  }]
72
106
  };
73
- return {
107
+ return opts.redirect?.(path, args.kind) ?? {
74
108
  path,
75
109
  namespace: 'zip'
76
110
  };
77
111
  });
112
+ b.onLoad({
113
+ filter: /.*/,
114
+ namespace: VIRTUAL
115
+ }, args => ({
116
+ contents: opts.virtual?.[args.path.slice(VIRTUAL.length + 1)] ?? '',
117
+ loader: 'js'
118
+ }));
119
+ // 다른 chunk를 부르는 import: 페이지의 모듈 목록에서 꺼낸다 (CommonJS 모양이라 esbuild가 이름을 그대로 이어 줌)
120
+ b.onLoad({
121
+ filter: /.*/,
122
+ namespace: CHUNK_REF
123
+ }, args => ({
124
+ contents: `module.exports = __ecdk_req(${json(args.path)});`,
125
+ loader: 'js'
126
+ }));
78
127
  b.onLoad({
79
128
  filter: /.*/,
80
129
  namespace: 'zip'
@@ -87,9 +136,8 @@ function zipFiles(byPath, page) {
87
136
  }]
88
137
  };
89
138
  const text = decoder.decode(file.data);
90
- // 묶으면 import.meta.url이 페이지 주소가 된다. 원래 파일 주소로 두어 new URL('./x', import.meta.url)이 그대로 맞게.
91
- // 하위 폴더 페이지는 깊이만큼 올라가고, <base href>와 상관없도록 페이지 주소(location.href) 기준으로
92
- const contents = text.replaceAll('import.meta.url', `new URL(${JSON.stringify(upFrom(page) + args.path)}, location.href).href`);
139
+ // 묶으면 import.meta.url이 페이지 주소가 된다. 원래 파일 주소로 두어 new URL('./x', import.meta.url)이 그대로 맞게
140
+ const contents = text.replaceAll('import.meta.url', opts.metaUrl(args.path));
93
141
  return {
94
142
  contents,
95
143
  loader: /\.json$/i.test(args.path) ? 'json' : 'js'
@@ -98,30 +146,93 @@ function zipFiles(byPath, page) {
98
146
  }
99
147
  };
100
148
  }
101
- async function bundle(entry, page, byPath, opts) {
149
+ /** 페이지에 넣는 묶음의 import.meta.url: 하위 폴더 페이지는 깊이만큼 올라가고, <base href>와 상관없도록 페이지 주소 기준 */
150
+ const pageMetaUrl = page => path => `new URL(${json(upFrom(page) + path)}, location.href).href`;
151
+ function esbuildError(entry, e) {
152
+ return e.errors?.[0]?.text ?? e.message ?? `${entry}: esbuild 오류`;
153
+ }
154
+ const baseOptions = opts => ({
155
+ ...(opts.workingDir ? {
156
+ absWorkingDir: opts.workingDir
157
+ } : {}),
158
+ // minify를 켜면 실제로 실행되는 묶음 코드를 줄인다 (원본 JS는 이제 실행되지 않음)
159
+ minify: opts.minify === true,
160
+ // sourcemap: 묶은 본문 끝에 inline map (chunk의 inline map을 이어 받아 원본 파일을 가리킴)
161
+ ...(opts.sourcemap ? {
162
+ sourcemap: 'inline'
163
+ } : {}),
164
+ // 라이선스 주석(/*! · @license · @preserve)은 줄여도 묶음 끝에 모아 남긴다 (넣은 라이브러리의 고지 의무)
165
+ legalComments: 'eof',
166
+ bundle: true,
167
+ target: 'es2022',
168
+ write: false,
169
+ logLevel: 'silent'
170
+ });
171
+ /** 묶은 코드의 표시한 import()를 나중에 받는 함수로 */
172
+ const rewriteLazyImports = code => code.replace(LAZY_IMPORT, (_, _q, path) => `__ecdk_load(${json(path)})`);
173
+ /** 나중에 받는 chunk로 가는 import는 표시만 남기고(묶지 않음), 다른 chunk를 부르는 것은 모듈 목록에서 */
174
+ function lazyRedirect(lazy, chunks, self) {
175
+ return (path, kind) => {
176
+ if (path === self) return undefined;
177
+ if (kind === 'dynamic-import' && (lazy.has(path) || self !== undefined && chunks.has(path))) return {
178
+ path: LAZY_PREFIX + path,
179
+ external: true
180
+ };
181
+ if (self !== undefined && chunks.has(path)) return {
182
+ path,
183
+ namespace: CHUNK_REF
184
+ };
185
+ return undefined;
186
+ };
187
+ }
188
+ /** 페이지에 넣을 묶음 (ESM). plan이 있으면 나중에 받는 chunk는 빼고, 그 chunk가 부르는 chunk를 모듈 목록에 올린다 */
189
+ async function bundle(entry, page, byPath, opts, plan) {
190
+ // 모듈 목록 등록을 화면 진입 파일보다 먼저: 화면 코드가 top-level await 중에 나중에 받는 chunk를 부를 수 있다
191
+ const virtual = plan ? {
192
+ page: `import "${VIRTUAL}:reg";\nimport ${json(entry)};\n`,
193
+ reg: plan.shared.map((p, i) => `import * as m${i} from ${json(p)};\n`).join('') + `const r = globalThis.__ecdk_lazy;\n` + plan.shared.map((p, i) => `r.e[${json(p)}] = m${i};\n`).join('')
194
+ } : undefined;
102
195
  const r = await build({
103
- entryPoints: [entry],
104
- ...(opts.workingDir ? {
105
- absWorkingDir: opts.workingDir
106
- } : {}),
107
- // minify를 켜면 실제로 실행되는 묶음 코드를 줄인다 (원본 JS는 이제 실행되지 않음)
108
- minify: opts.minify === true,
109
- // sourcemap: 묶은 본문 끝에 inline map (chunk의 inline map을 이어 받아 원본 파일을 가리킴)
110
- ...(opts.sourcemap ? {
111
- sourcemap: 'inline'
112
- } : {}),
113
- // 라이선스 주석(/*! · @license · @preserve)은 줄여도 묶음 끝에 모아 남긴다 (넣은 라이브러리의 고지 의무)
114
- legalComments: 'eof',
115
- bundle: true,
196
+ ...baseOptions(opts),
197
+ entryPoints: [plan ? `${VIRTUAL}:page` : entry],
116
198
  format: 'esm',
117
- target: 'es2022',
118
- write: false,
119
- logLevel: 'silent',
120
- plugins: [zipFiles(byPath, page)]
199
+ plugins: [zipFiles(byPath, {
200
+ metaUrl: pageMetaUrl(page),
201
+ redirect: plan ? lazyRedirect(plan.lazy, plan.chunks) : undefined,
202
+ virtual
203
+ })]
121
204
  }).catch(e => {
122
- throw new Error(`${entry}를 묶지 못했습니다: ${e.errors?.[0]?.text ?? e.message ?? 'esbuild 오류'}. LXP에서는 모듈 스크립트를 따로 받을 수 없어 build가 HTML 안에 묶어 넣습니다.`);
205
+ throw new Error(`${entry}를 묶지 못했습니다: ${esbuildError(entry, e)}. LXP에서는 모듈 스크립트를 따로 받을 수 없어 build가 HTML 안에 묶어 넣습니다.`);
123
206
  });
124
- return r.outputFiles[0]?.text ?? '';
207
+ const code = r.outputFiles[0]?.text ?? '';
208
+ return plan ? rewriteLazyImports(code) : code;
209
+ }
210
+ /**
211
+ * 나중에 받는 chunk 하나를 일반 스크립트 파일로: 실행하지 않고 함수로 모듈 목록에 올려 두면, `__ecdk_load`가
212
+ * 필요한 파일을 다 받은 뒤 실행한다. 다른 chunk는 `__ecdk_req`로, `import.meta.url`은 zip 최상위(`__ecdk_root`) 기준으로
213
+ */
214
+ async function bundleLazy(path, byPath, chunks, opts) {
215
+ const r = await build({
216
+ ...baseOptions(opts),
217
+ entryPoints: [path],
218
+ format: 'iife',
219
+ globalName: '__ecdk_out',
220
+ plugins: [zipFiles(byPath, {
221
+ metaUrl: p => `new URL(${json(p)}, __ecdk_root).href`,
222
+ redirect: lazyRedirect(new Set(), chunks, path)
223
+ })]
224
+ });
225
+ const code = rewriteLazyImports(r.outputFiles[0]?.text ?? '');
226
+ // 첫 줄에 붙여 sourcemap 줄 번호가 그대로 맞게. 끝의 주석(//# sourceMappingURL) 뒤에 오도록 return은 다음 줄
227
+ return `${LAZY_FILE_MARK}(globalThis.__ecdk_lazy??={d:{},e:{},m:{},p:{}}).d[${json(path)}]=function(__ecdk_req,__ecdk_root){${code}\nreturn __ecdk_out};\n`;
228
+ }
229
+ /**
230
+ * 페이지의 나중에 받는 chunk 불러오기 (일반 스크립트). deps: chunk마다 정적으로 부르는 chunk.
231
+ * 화면 묶음의 모듈(e)은 namespace라 `__esModule`을 붙여 esbuild의 CommonJS 이음(default)이 맞게 감싼다
232
+ */
233
+ function loaderPrelude(page, deps) {
234
+ const code = `(()=>{const g=globalThis,R=g.__ecdk_lazy??={d:{},e:{},m:{},p:{}},root=new URL(${json(upFrom(page) || './')},location.href).href,D=Object.assign(R.D??={},${json(deps)});const wrap=n=>{const o={};Object.defineProperty(o,'__esModule',{value:true});for(const k of Object.keys(n))Object.defineProperty(o,k,{enumerable:true,get:()=>n[k]});return o};const req=p=>{if(p in R.m)return R.m[p];if(R.e[p])return R.m[p]=wrap(R.e[p]);const f=R.d[p];if(!f)throw new Error('ecdk: 불러오지 못한 파일 '+p);return R.m[p]=f(req,root)};const need=p=>{const s=new Set,v=q=>{if(s.has(q)||R.e[q])return;s.add(q);(D[q]||[]).forEach(v)};v(p);return[...s]};const get=p=>R.p[p]??=new Promise((ok,no)=>{const s=document.createElement('script');s.src=new URL(p,root).href;s.onload=ok;s.onerror=()=>{delete R.p[p];no(new Error('ecdk: 파일을 받지 못했습니다 '+p))};(document.head||document.documentElement).append(s)});g.__ecdk_load??=async p=>{await Promise.all(need(p).filter(q=>!R.d[q]).map(get));return req(p)}})();`;
235
+ return `<script ${BUNDLE_ATTR}="loader">${escapeInline(code)}</script>`;
125
236
  }
126
237
  /** zip 안 JSON을 넣어 두고, 그 주소를 fetch하면 넣어 둔 내용을 돌려준다 */
127
238
  function jsonPrelude(files, page) {
@@ -148,11 +259,57 @@ function jsonPrelude(files, page) {
148
259
  function stripCrossorigin(html) {
149
260
  return html.replace(/<(?:link|script)\b[^>]*>/gi, tag => tag.replace(/\s+crossorigin(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?(?=[\s/>])/gi, ''));
150
261
  }
262
+ /**
263
+ * 진입 chunk에서 정적 import로 닿는 chunk(열 때 실행)와 그 밖에 동적 import()로 닿는 chunk(나중에)를 나눈다.
264
+ * 나누지 않으면 null (작음), 나눌 수 없으면 이유
265
+ */
266
+ function planLazy(entry, graph, byPath) {
267
+ if (!graph.has(entry)) return null;
268
+ const eager = new Set();
269
+ const visitStatic = p => {
270
+ if (eager.has(p) || !graph.has(p)) return;
271
+ eager.add(p);
272
+ for (const q of graph.get(p)?.imports ?? []) visitStatic(q);
273
+ };
274
+ visitStatic(entry);
275
+ const lazy = new Set();
276
+ const visitAll = p => {
277
+ for (const q of [...(graph.get(p)?.imports ?? []), ...(graph.get(p)?.dynamicImports ?? [])]) {
278
+ if (eager.has(q) || lazy.has(q) || !graph.has(q)) continue;
279
+ lazy.add(q);
280
+ visitAll(q);
281
+ }
282
+ };
283
+ for (const p of eager) visitAll(p);
284
+ const bytes = [...lazy].reduce((s, p) => s + (byPath.get(p)?.data.byteLength ?? 0), 0);
285
+ if (bytes < LAZY_MIN_BYTES) return null;
286
+ // 정적 import 순환: 모듈 목록은 실행을 마친 chunk만 돌려주므로 서로 부르면 맞지 않는다
287
+ const state = new Map();
288
+ const cyclic = p => {
289
+ if (state.get(p) === 'done' || !lazy.has(p)) return false;
290
+ if (state.get(p) === 'visiting') return true;
291
+ state.set(p, 'visiting');
292
+ const found = (graph.get(p)?.imports ?? []).some(cyclic);
293
+ state.set(p, 'done');
294
+ return found;
295
+ };
296
+ if ([...lazy].some(cyclic)) return '나중에 받을 chunk끼리 서로 import함 (순환)';
297
+ const shared = new Set();
298
+ for (const p of lazy) for (const q of [...(graph.get(p)?.imports ?? []), ...(graph.get(p)?.dynamicImports ?? [])]) if (eager.has(q)) shared.add(q);
299
+ return {
300
+ lazy,
301
+ chunks: new Set(graph.keys()),
302
+ shared: [...shared].sort()
303
+ };
304
+ }
151
305
  /** HTML의 모듈 스크립트(src)를 묶어 본문으로 넣는다. 바뀐 파일만 새로 만들어 돌려준다 */
152
306
  async function inlineModuleScripts(files, opts = {}) {
153
307
  const byPath = new Map(files.map(f => [f.path, f]));
154
308
  const pages = [];
155
309
  const out = [];
310
+ /** 나중에 받는 파일 (chunk 경로 → 일반 스크립트 내용). 여러 화면이 같은 파일을 같이 쓴다 */
311
+ const lazyCode = new Map();
312
+ const pageLazy = new Map();
156
313
  for (const f of files) {
157
314
  if (!/\.html?$/i.test(f.path)) {
158
315
  out.push(f);
@@ -178,30 +335,83 @@ async function inlineModuleScripts(files, opts = {}) {
178
335
  }
179
336
  let next = '';
180
337
  let last = 0;
338
+ const lazyHere = {
339
+ files: new Set(),
340
+ skipped: undefined
341
+ };
342
+ const deps = {};
181
343
  for (const [i, m] of scripts.entries()) {
182
344
  const src = attr(m[1] ?? '', 'src') ?? '';
183
345
  const entry = resolveRef(f.path, src.replace(/[?#].*$/, ''));
184
346
  if (entry === null || !byPath.has(entry)) throw new Error(`${f.path}의 모듈 스크립트 파일이 없습니다: ${src}`);
185
- const code = await bundle(entry, f.path, byPath, opts);
347
+ const planned = opts.chunks ? planLazy(entry, opts.chunks, byPath) : null;
348
+ let plan = typeof planned === 'string' ? undefined : planned ?? undefined;
349
+ if (typeof planned === 'string') lazyHere.skipped = planned;
350
+ // 나중에 받는 chunk를 먼저 일반 스크립트로 묶어 본다. 하나라도 안 되면(top-level await 등) 이 화면은 나누지 않는다
351
+ if (plan) {
352
+ try {
353
+ // 다 묶은 뒤에 넣는다: 하나라도 실패하면 이 화면의 것은 zip에 남기지 않음
354
+ const built = new Map();
355
+ for (const p of plan.lazy) if (!lazyCode.has(p)) built.set(p, await bundleLazy(p, byPath, plan.chunks, opts));
356
+ for (const [p, code] of built) lazyCode.set(p, code);
357
+ } catch (e) {
358
+ lazyHere.skipped = `나중에 받는 파일로 묶지 못함: ${esbuildError(entry, e)}`;
359
+ plan = undefined;
360
+ }
361
+ }
362
+ const code = await bundle(entry, f.path, byPath, opts, plan);
186
363
  next += html.slice(last, m.index);
187
364
  if (i === 0) next += jsonPrelude(files, f.path);
365
+ if (plan) {
366
+ for (const p of plan.lazy) {
367
+ lazyHere.files.add(p);
368
+ deps[p] = (opts.chunks?.get(p)?.imports ?? []).filter(q => plan.chunks.has(q));
369
+ }
370
+ next += loaderPrelude(f.path, deps);
371
+ }
188
372
  // data-ecdk-bundle: 원본(ecdk-ignore 주석 포함)을 이미 검사했으니 zip 검사에서 이 본문은 다시 보지 않는다
189
373
  next += `<script type="module" ${BUNDLE_ATTR}="${entry}">\n${escapeInline(code)}</script>`;
190
374
  last = (m.index ?? 0) + m[0].length;
191
375
  }
192
376
  next += html.slice(last);
193
377
  pages.push(f.path);
378
+ pageLazy.set(f.path, lazyHere);
194
379
  out.push({
195
380
  ...f,
196
381
  data: encoder.encode(next)
197
382
  });
198
383
  }
384
+ // 나중에 받는 chunk는 Vite chunk 파일 자리에 일반 스크립트로 바꿔 넣는다 (플러그인이 이 경로만 남김)
385
+ const final = out.map(f => {
386
+ const code = lazyCode.get(f.path);
387
+ return code === undefined ? f : {
388
+ ...f,
389
+ data: encoder.encode(code)
390
+ };
391
+ });
392
+ const byFinal = new Map(final.map(f => [f.path, f]));
393
+ const screens = screenSizes(final).map(s => {
394
+ const lazy = pageLazy.get(s.page);
395
+ const lazyFiles = [...(lazy?.files ?? [])].sort();
396
+ return {
397
+ page: s.page,
398
+ scriptBytes: s.scriptBytes,
399
+ styleBytes: s.styleBytes,
400
+ lazyFiles,
401
+ lazyBytes: lazyFiles.reduce((n, p) => n + (byFinal.get(p)?.data.byteLength ?? 0), 0),
402
+ ...(lazy?.skipped ? {
403
+ lazySkipped: lazy.skipped
404
+ } : {})
405
+ };
406
+ });
199
407
  return {
200
- files: out,
408
+ files: final,
201
409
  report: {
202
- pages
410
+ pages,
411
+ screens,
412
+ lazyFiles: [...lazyCode.keys()].sort()
203
413
  }
204
414
  };
205
415
  }
206
416
 
207
- export { BUNDLE_ATTR, inlineModuleScripts };
417
+ export { BUNDLE_ATTR, LAZY_MIN_BYTES, inlineModuleScripts };
package/es/dev/check.d.ts CHANGED
@@ -6,6 +6,11 @@ export declare const CHECK_VIEWPORTS: {
6
6
  readonly desktop: "100%";
7
7
  readonly mobile: "360px";
8
8
  };
9
+ /** --theme: 콘텐츠 문서에 EDS 테마(data-eds-theme)를 붙여 찍는다. 없으면 프로젝트 그대로 */
10
+ export declare const CHECK_THEMES: readonly ["light", "dark"];
11
+ export type CheckTheme = (typeof CHECK_THEMES)[number];
12
+ /** --step: 키트 스테퍼가 있는 화면은 단계마다 찍는다 ('all' 또는 1부터 센 단계 번호) */
13
+ export type CheckSteps = 'all' | number[];
9
14
  export type CheckViewport = keyof typeof CHECK_VIEWPORTS;
10
15
  /** 화면 하나를 기다리는 최대 시간. 넘으면 그때 모습으로 기록한다 */
11
16
  export declare const SCREEN_WAIT_MS = 8000;
@@ -25,6 +30,14 @@ export interface ScreenResult {
25
30
  /** 콘텐츠 · 흉내 API의 4xx · 5xx "상태 경로" */
26
31
  failedRequests: string[];
27
32
  overflowX: boolean;
33
+ /** --theme로 찍은 테마 (없으면 프로젝트 그대로) */
34
+ theme?: CheckTheme;
35
+ /** --step으로 찍은 단계 (1부터). 스테퍼가 없는 화면 · --step 없이는 없음 */
36
+ step?: number;
37
+ /** --step에 적은 단계가 없을 때 (스테퍼 없음 · 단계 수 밖) 그 안내 */
38
+ missingStep?: string;
39
+ /** 키트 스테퍼 · 레이아웃 배치 문제 (layoutProbe). 옛 결과에는 없음 */
40
+ layout?: LayoutFinding[];
28
41
  /** 프로젝트 기준 경로 (/ 구분). 찍지 못했으면 null */
29
42
  screenshot: string | null;
30
43
  ms: number;
@@ -61,6 +74,19 @@ export type Finding = {
61
74
  level: 'fail' | 'warn';
62
75
  message: string;
63
76
  };
77
+ /**
78
+ * 키트 스테퍼 · 레이아웃 배치 문제. id는 화면 검사 규칙 이름(render.*)
79
+ * - render.covered-control (fail): 스테퍼 버튼 가운데 점(elementFromPoint)에 다른 요소가 있음,
80
+ * 키트 제출 바(.ec-submitbar) 버튼이 스테퍼 버튼 줄과 겹침
81
+ * (warn): 칸 안 작성자 조작(버튼 · 입력 · 슬라이더)이 키트 스테퍼 버튼에 깔림 (모바일 아래 줄 등)
82
+ * - render.readout-below · render.controls-below (warn): stage 레이아웃의 실시간 값 · 조작이 첫 화면 밖
83
+ * - render.outside-region (warn): split · stage · media 레이아웃 바로 아래에 영역(data-ec-region) 밖 내용
84
+ */
85
+ export type LayoutFinding = {
86
+ id: string;
87
+ level: 'fail' | 'warn';
88
+ message: string;
89
+ };
64
90
  /** 화면 하나의 문제. fail: 오류 · 막힘 · 빈 화면, warn: 불러오는 중이 남음 · 가로 넘침 */
65
91
  export declare function findingsOf(r: ScreenResult): Finding[];
66
92
  export declare function statusOf(r: ScreenResult): 'ok' | 'warn' | 'fail';
@@ -73,6 +99,10 @@ export interface RunCheckOptions {
73
99
  /** 없으면 defaultScreens */
74
100
  screens?: CheckScreen[];
75
101
  viewports?: CheckViewport[];
102
+ /** 없으면 프로젝트 테마 그대로 한 번 */
103
+ themes?: CheckTheme[];
104
+ /** 없으면 첫 화면만 */
105
+ steps?: CheckSteps;
76
106
  }
77
107
  /** 프로젝트에 없는 화면을 고른 경우 (사용법 오류) */
78
108
  export declare class ScreenNotFoundError extends Error {