@eliceio/cdk-cli 1.2.1 → 1.3.0-contenttypes.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 (169) hide show
  1. package/README.md +63 -53
  2. package/es/cli.js +11 -2
  3. package/es/commands/build/index.js +12 -0
  4. package/es/commands/create/index.js +2 -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/commands/doctor/index.js +6 -2
  10. package/es/core/config.d.ts +42 -9
  11. package/es/core/config.js +217 -12
  12. package/es/core/project-check.d.ts +3 -2
  13. package/es/core/project-check.js +14 -3
  14. package/es/core/regex.d.ts +11 -0
  15. package/es/core/regex.js +41 -0
  16. package/es/core/sandbox.d.ts +26 -0
  17. package/es/core/sandbox.js +240 -30
  18. package/es/dev/assets.d.ts +80 -0
  19. package/es/dev/assets.js +240 -0
  20. package/es/dev/check.d.ts +30 -0
  21. package/es/dev/check.js +224 -34
  22. package/es/dev/grading.d.ts +49 -14
  23. package/es/dev/grading.js +109 -29
  24. package/es/dev/host-page.js +27 -3
  25. package/es/dev/inject.d.ts +2 -1
  26. package/es/dev/inject.js +10 -2
  27. package/es/dev/mock-api.d.ts +26 -3
  28. package/es/dev/mock-api.js +219 -40
  29. package/es/dev/server.d.ts +12 -1
  30. package/es/dev/server.js +115 -9
  31. package/es/engines/vite/index.js +1 -1
  32. package/es/engines/vite/plugin.d.ts +2 -0
  33. package/es/engines/vite/plugin.js +33 -5
  34. package/es/rules/answers.d.ts +13 -0
  35. package/es/rules/answers.js +94 -0
  36. package/es/rules/check.js +70 -1
  37. package/es/rules/index.d.ts +1 -0
  38. package/es/rules/index.js +1 -0
  39. package/es/rules/size.d.ts +31 -0
  40. package/es/rules/size.js +58 -0
  41. package/es/rules/types.d.ts +12 -0
  42. package/es/rules.json.js +2 -2
  43. package/package.json +2 -2
  44. package/rules.json +34 -5
  45. package/skills/_shared/always.md +3 -3
  46. package/skills/_shared/references/00-what-the-person-decides.md +1 -1
  47. package/skills/_shared/references/02-design-the-material.md +10 -7
  48. package/skills/_shared/references/03-create-the-project.md +10 -8
  49. package/skills/_shared/references/04-rules.md +1 -1
  50. package/skills/_shared/references/05-screen-code.md +52 -23
  51. package/skills/_shared/references/06-using-the-quiz-template.md +7 -6
  52. package/skills/_shared/references/08-fix-check-errors.md +23 -22
  53. package/skills/_shared/references/09-check.md +8 -6
  54. package/skills/_shared/references/12-upload-with-the-material-mcp.md +13 -13
  55. package/skills/_shared/references/13-edit-screen-design.md +122 -0
  56. package/skills/_shared/references/14-layouts.md +96 -0
  57. package/skills/elice-content-check/SKILL.md +2 -2
  58. package/skills/elice-content-create/SKILL.md +1 -1
  59. package/skills/elice-content-migrate/SKILL.md +1 -1
  60. package/skills/elice-content-publish/SKILL.md +1 -1
  61. package/templates/_shared/lib/cdk-mock.d.ts +47 -3
  62. package/templates/_shared/lib/cdk-mock.js +293 -15
  63. package/templates/_shared/lib/elice-content-editor.js +89 -58
  64. package/templates/_shared/lib/elice-content.css +1313 -126
  65. package/templates/_shared/lib/elice-content.d.ts +222 -23
  66. package/templates/_shared/lib/elice-content.js +1176 -88
  67. package/templates/_shared/lib/icons/empty-content.d.ts +2 -0
  68. package/templates/_shared/lib/icons/empty-content.js +11 -0
  69. package/templates/_shared/lib/icons/file-video.d.ts +2 -0
  70. package/templates/_shared/lib/icons/file-video.js +11 -0
  71. package/templates/_shared/lib/icons/file.d.ts +2 -0
  72. package/templates/_shared/lib/icons/file.js +11 -0
  73. package/templates/blank/README.md +6 -4
  74. package/templates/blank/edit.html +8 -2
  75. package/templates/blank/index.html +6 -1
  76. package/templates/blank/instructor.html +6 -1
  77. package/templates/blank/screens/instructor.js +8 -2
  78. package/templates/blank/screens/learn.js +1 -1
  79. package/templates/blank/template.json +1 -1
  80. package/templates/document/README.md +92 -0
  81. package/templates/document/commentary.txt +2 -0
  82. package/templates/document/core/dom.d.ts +13 -0
  83. package/templates/document/core/dom.js +83 -0
  84. package/templates/document/core/file-type.d.ts +21 -0
  85. package/templates/document/core/file-type.js +85 -0
  86. package/templates/document/core/group-3d.d.ts +20 -0
  87. package/templates/document/core/group-3d.js +256 -0
  88. package/templates/document/core/inline-edit.d.ts +15 -0
  89. package/templates/document/core/inline-edit.js +377 -0
  90. package/templates/document/core/load.d.ts +13 -0
  91. package/templates/document/core/load.js +40 -0
  92. package/templates/document/core/pdf-options.d.ts +9 -0
  93. package/templates/document/core/pdf-options.js +36 -0
  94. package/templates/document/core/pdf-worker.d.ts +24 -0
  95. package/templates/document/core/pdf-worker.js +122 -0
  96. package/templates/document/core/pdf.d.ts +12 -0
  97. package/templates/document/core/pdf.js +190 -0
  98. package/templates/document/core/pptx-edit.d.ts +14 -0
  99. package/templates/document/core/pptx-edit.js +137 -0
  100. package/templates/document/core/pptx-fonts.d.ts +5 -0
  101. package/templates/document/core/pptx-fonts.js +115 -0
  102. package/templates/document/core/pptx-media.d.ts +18 -0
  103. package/templates/document/core/pptx-media.js +83 -0
  104. package/templates/document/core/pptx-view.d.ts +5 -0
  105. package/templates/document/core/pptx-view.js +185 -0
  106. package/templates/document/core/settings.d.ts +25 -0
  107. package/templates/document/core/settings.js +86 -0
  108. package/templates/document/core/slide-edges.d.ts +3 -0
  109. package/templates/document/core/slide-edges.js +82 -0
  110. package/templates/document/core/viewer.d.ts +28 -0
  111. package/templates/document/core/viewer.js +159 -0
  112. package/templates/document/edit.html +17 -0
  113. package/templates/document/gitignore +4 -0
  114. package/templates/document/index.html +18 -0
  115. package/templates/document/metadata.json +9 -0
  116. package/templates/document/package.json +17 -0
  117. package/templates/document/public/fonts/OFL-Caladea.txt +93 -0
  118. package/templates/document/public/fonts/OFL-Carlito.txt +93 -0
  119. package/templates/document/public/fonts/caladea-latin-400-normal.woff2 +0 -0
  120. package/templates/document/public/fonts/caladea-latin-700-normal.woff2 +0 -0
  121. package/templates/document/public/fonts/carlito-latin-400-normal.woff2 +0 -0
  122. package/templates/document/public/fonts/carlito-latin-700-normal.woff2 +0 -0
  123. package/templates/document/screens/edit.js +574 -0
  124. package/templates/document/screens/learn.js +61 -0
  125. package/templates/document/styles.css +644 -0
  126. package/templates/document/template.json +6 -0
  127. package/templates/document/ui/templates/edit.js +82 -0
  128. package/templates/document/ui/templates/page.js +11 -0
  129. package/templates/document/ui/templates/viewer.js +41 -0
  130. package/templates/document/ui/texts.d.ts +3 -0
  131. package/templates/document/ui/texts.js +62 -0
  132. package/templates/document/ui/theme.css +69 -0
  133. package/templates/quiz/README.md +32 -14
  134. package/templates/quiz/core/behaviors.d.ts +17 -7
  135. package/templates/quiz/core/behaviors.js +40 -53
  136. package/templates/quiz/core/editor.d.ts +27 -2
  137. package/templates/quiz/core/editor.js +412 -11
  138. package/templates/quiz/core/markdown.d.ts +19 -0
  139. package/templates/quiz/core/markdown.js +225 -11
  140. package/templates/quiz/core/model.d.ts +40 -3
  141. package/templates/quiz/core/model.js +112 -5
  142. package/templates/quiz/core/rich-text.d.ts +18 -0
  143. package/templates/quiz/core/rich-text.js +469 -0
  144. package/templates/quiz/edit.html +12 -3
  145. package/templates/quiz/index.html +12 -3
  146. package/templates/quiz/public/img/mascot-half.webp +0 -0
  147. package/templates/quiz/screens/edit.js +331 -49
  148. package/templates/quiz/screens/learn.js +147 -15
  149. package/templates/quiz/styles.css +1244 -622
  150. package/templates/quiz/template.json +9 -2
  151. package/templates/quiz/ui/templates/edit.d.ts +19 -5
  152. package/templates/quiz/ui/templates/edit.js +371 -77
  153. package/templates/quiz/ui/templates/group.js +19 -8
  154. package/templates/quiz/ui/templates/order.js +25 -24
  155. package/templates/quiz/ui/templates/page.js +33 -8
  156. package/templates/quiz/ui/templates/question.js +6 -4
  157. package/templates/quiz/ui/texts.js +91 -26
  158. package/templates/quiz/ui/theme.css +8 -9
  159. package/templates/steps/README.md +77 -0
  160. package/templates/steps/commentary.txt +7 -0
  161. package/templates/steps/edit.html +21 -0
  162. package/templates/steps/gitignore +4 -0
  163. package/templates/steps/index.html +69 -0
  164. package/templates/steps/metadata.json +9 -0
  165. package/templates/steps/package.json +13 -0
  166. package/templates/steps/screens/edit.js +32 -0
  167. package/templates/steps/screens/learn.js +108 -0
  168. package/templates/steps/styles.css +54 -0
  169. 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 };
@@ -0,0 +1,80 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ /**
3
+ * 자료 파일(PDF · PPTX 문서, PNG · JPEG · WebP · GIF 이미지) 올리기 · 보기 흉내 (dev 전용). 서버 스펙과 같은 흐름:
4
+ * 1. 편집 화면 SDK `assets.post` → 흉내 API `POST /storage/upload-url` `{ key: "asset.pdf" | "asset.png" | …,
5
+ * content_length, content_type }` → `{ upload_url, key: "assets/{material_id}/{asset_id}.{ext}" }`
6
+ * 2. SDK가 `upload_url`로 PUT → 콘텐츠 서버 `/__ecdk/blob/{asset_id}.{ext}`가 받아 `.ecdk/assets/`에 둔다
7
+ * (운영은 Azure Blob, 다른 출처)
8
+ * 3. 흉내 API `GET /materials/{id}`의 `current_version`(edit 토큰은 `draft`도) `asset_base_url`
9
+ * (운영처럼 자료 API 출처의 서명 경로까지, dev: `{API}/s/dev/`) + 저장 경로 `assets/{material_id}/{asset_key}`로
10
+ * 흉내 API가 내준다 (Range 206, pdf.js가 필요한 부분만 받음). 자료 API 출처는 운영 CSP `connect-src`에 있다
11
+ * 운영 콘텐츠 CSP `connect-src`에는 Blob 출처가 없어 2의 PUT이 막힌다. dev는 이 경로만
12
+ * `connect-src`에 더한다 (server.ts `devOnlyConnectSrc`). `.ecdk/`는 점 폴더라 감시 · zip에서 빠진다.
13
+ */
14
+ /** 받은 파일을 두는 곳 (프로젝트 기준) */
15
+ export declare const ASSETS_DIR = ".ecdk/assets";
16
+ /** 콘텐츠 서버가 PUT을 받는 경로 (운영의 Blob 업로드 URL 자리) */
17
+ export declare const DEV_BLOB_PREFIX = "/__ecdk/blob/";
18
+ /** 흉내 API 아래 서명 경로 (asset_base_url 끝, 운영 `https://{API}/s/{서명}/` 자리) */
19
+ export declare const ASSET_SIGNED_PATH = "/s/dev/";
20
+ /**
21
+ * 콘텐츠 주소를 직접 열어 mock SDK로 돌 때 쓰는 dev 전용 upload-url (호스트, 토큰 없음, 결과는 /storage/upload-url과 같음).
22
+ * ecdk dev는 작성자 PC에서만 돌고 올린 파일은 작성자 프로젝트(.ecdk/assets/)에만 남아 막을 대상이 없다
23
+ */
24
+ export declare const MOCK_UPLOAD_URL_PATH = "/__ecdk/mock-upload-url";
25
+ /** asset_base_url 아래 저장 경로: `assets/{material_id}/` (+ asset_key) */
26
+ export declare const assetStoragePath: (materialId: string) => string;
27
+ /** 서버 한도: 문서(asset.pdf · asset.pptx) 최대 95MB */
28
+ export declare const MAX_ASSET_BYTES: number;
29
+ /** 서버 한도: 이미지(asset.png · .jpg · .jpeg · .webp · .gif) 최대 10MB. SVG는 받지 않는다 */
30
+ export declare const MAX_IMAGE_BYTES: number;
31
+ /** upload-url `key` → 확장자 · Content-Type · 최대 크기 */
32
+ export declare const ASSET_UPLOAD_KINDS: Readonly<Record<string, {
33
+ ext: string;
34
+ type: string;
35
+ maxBytes: number;
36
+ }>>;
37
+ export type UploadUrlResult = {
38
+ ok: true;
39
+ data: {
40
+ upload_url: string;
41
+ key: string;
42
+ expires_in: number;
43
+ };
44
+ } | {
45
+ ok: false;
46
+ status: number;
47
+ code: string;
48
+ message: string;
49
+ details?: unknown[];
50
+ };
51
+ /** 발급한 업로드 URL (asset_key → 허용 크기). 한 번 PUT하면 지운다 */
52
+ export type PendingUploads = Map<string, number>;
53
+ /**
54
+ * `POST /storage/upload-url` 흉내: 종류 · 형식 · 크기를 확인하고 PUT할 주소를 준다. 오류는 서버처럼
55
+ * (SDK가 바꾸는 코드): 모르는 key · 크기 0은 INVALID_INPUT, 다른 content_type은 INVALID_INPUT + `unsupported_content_type`
56
+ * (→ file_invalid_type), 한도(문서 95MB · 이미지 10MB) 초과는 MATERIAL_PACKAGE_TOO_LARGE (→ file_invalid_size).
57
+ * SVG(asset.svg)는 모르는 key라 INVALID_INPUT (서버와 같음)
58
+ * @param opts.uploadOrigin PUT을 받는 콘텐츠 출처 (운영은 Blob 출처)
59
+ */
60
+ export declare function createUploadUrl(body: unknown, opts: {
61
+ materialId: string;
62
+ uploadOrigin: string;
63
+ pending: PendingUploads;
64
+ }): UploadUrlResult;
65
+ /**
66
+ * 콘텐츠 서버 `PUT /__ecdk/blob/{asset_key}`: 발급한 주소만, 알린 크기까지 받아 `.ecdk/assets/{asset_key}`에 둔다 (201).
67
+ * 처리했으면 true, 이 경로가 아니면 false
68
+ */
69
+ export declare function handleBlobPut(req: IncomingMessage, res: ServerResponse, pathname: string, opts: {
70
+ dir: string;
71
+ pending: PendingUploads;
72
+ log?: (m: string) => void;
73
+ }): Promise<boolean>;
74
+ /**
75
+ * 흉내 API `GET · HEAD /s/dev/assets/{material_id}/{asset_key}`. Range(206)를 받는다.
76
+ * 받은 파일이 없으면 false
77
+ */
78
+ export declare function serveAsset(req: IncomingMessage, res: ServerResponse, assetKey: string, dir: string): Promise<boolean>;
79
+ /** "처음 상태로": 받은 파일도 지운다 */
80
+ export declare const removeAssets: (dir: string) => Promise<void>;